I have the following code:
getData = async function (afgJSON) {
console.log("step 2")
await axios.post(process.env.afgEndPoint, afgJSON, {
headers: headers
})
.then((response) => {
console.log("step 3")
return response.data
})
.catch((e) => {
console.log("step 3")
return e.response.data
})
}
Which I call as this:
console.log("step 1")
let afgResponse = await common.getData(afgJSON);
console.log("step 4")
console.log(afgResponse)
afgResponse always is undefined, and the console.logs show the right order:
step 1
step 2
step 3
step 4
undefined
... but if I console.log response.data (.then), the response is fine.
I was reading other posts at stackoverflow about .then => with Axios but I still cant figure this out.
Thanks.
CodePudding user response:
You missed to return the result of axios call from the function "getData"
CodePudding user response:
getData = async function (afgJSON) {
try {
const { data } = await axios.post(process.env.afgEndPoint, afgJSON, {
headers: headers
})
return data
} catch (err) {
return err // return the data you want
}
}
You could also return directly axios.post and check
getData = async function (afgJSON) {
return axios.post(process.env.afgEndPoint, afgJSON, {
headers: headers
})
}
And in your other file =>
const { data: afgResponse } = await common.getData(afgJSON);
But you will have to handle the error in the other file