0

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.

Danielle
  • 1,386
  • 8
  • 22
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Konrad Oct 20 '22 at 21:34
  • `e.response.data` doesn't make any sense here, you already got `reponse.data` – Konrad Oct 20 '22 at 21:35
  • 1
    Hi Konrad. I know... e.response.data is actually where they return the data. The console.log shows up the JSON just fine. This is cause they coded the API in a way that any error produces a 500 – Danielle Oct 20 '22 at 21:37
  • messages: [ 'quoteId already exists' ], output: null, success: false – Danielle Oct 20 '22 at 21:38
  • return (e) will produce the same scenario. Console.logs follow "the order" just fine but always return undefined – Danielle Oct 20 '22 at 21:41

2 Answers2

2

You missed to return the result of axios call from the function "getData"

Bad Dobby
  • 811
  • 2
  • 8
  • 22
0
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

boubaks
  • 352
  • 2
  • 8