0

Not sure what I'm missing here but the console.log() line prints "Promise { }" instead of the JSON body from the response.
I believe that I'm doing something wrong with async/await.

My code (Express):

async function axiosPost(url, payload) {
   try {
      const res = await axios.post(url, payload);
      const data = await res.data;
      return data;
  } catch (error) {
      console.error(error);
  }
}

app.get('/data', (req, res) => {
    data = axiosPost('http://localhost:8080', {
        userpass: 'XXX',
        method: 'getdata'
     });
     console.log(data)
     res.status(200).send({
        message: data
    })
});

Any help is appreciated.

  • 1
    Possible duplicate of [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) – CertainPerformance Oct 23 '18 at 04:54
  • You are getting `promise` in `data` because you have not resolved `axiosPost`. You have to resolved this by using `then`. Please refer this link to understand how `promises` works https://javascript.info/promise-basics – Aabid Oct 23 '18 at 06:04

2 Answers2

1

replace your router with this. you were not using await while making an API call. Hope it helps.

app.get('/data', async (req, res) => {
    let data = await axiosPost('http://localhost:8080', {
        userpass: 'XXX',
        method: 'getdata'
     });
     console.log(data)
     res.status(200).send({
        message: data
    })
});
Atishay Jain
  • 1,425
  • 12
  • 22
0

You get that result because you didn't resolve the call to axiosPost() which is asynchronous. This can be solved in 2 ways, one by appending .then() to the axiosPost() call or simply awaiting it using the await keyword. See below:

async function axiosPost(url, payload) {
   try {
      const res = await axios.post(url, payload);
      const data = await res.data; // this is not required but you can leave as is
      return data;
  } catch (error) {
      console.error(error);
  }
}

// I converted the callback to an async function and
// also awaited the result from the call to axiosPost(),
// since that is an async function
app.get('/data', async (req, res) => {
    data = await axiosPost('http://localhost:8080', {
        userpass: 'XXX',
        method: 'getdata'
     });
     console.log(data)
     res.status(200).send({
        message: data
    })
});

// OR using `then()`

app.get('/data', (req, res) => {
    axiosPost('http://localhost:8080', {
        userpass: 'XXX',
        method: 'getdata'
     }).then((data) => {
      console.log(data);
      
      res.status(200).send({
        message: data
      });
    });
})
codejockie
  • 9,020
  • 4
  • 40
  • 46