[Fixed] Array of Promises still say pending after chaining on then function

Issue

I am currently working on a small express app where I am using axios to send/receive data from a github API. I am using insomnia to test sending the data as JSON to the github API in order to find specified user(s) profile information. This is how I am sending the data:

{
    "developers": ["person", "person"]
}

Here is my code:

    let results = req.body.developers
    results.map(async d => {
      await axios.get(`https://api.github.com/users/${d}`)
      .then((response => {
        console.log(response)
      }))
      .catch((err) => {
        console.log(err)
      })
    })
      let out = results.map(r => ({ name: r.data.name, bio: r.data.bio }));
      return res.send(JSON.stringify(out));

When I make a request, I receive my promises in an array, but they still say ‘Pending’. I thought that by chaining the then function to my get request within the results.map would solve this issue. What is wrong with my code?

Solution

You should use await Promise.all() on results, and assign the responses to some variable to use in your out array.

const results = req.body.developers
const responses = await Promise.all(results.map(async d => {
    const response = await axios.get(`https://api.github.com/users/${d}`);
    console.log(response);
    return response;
});
const out = responses.map(({ data } => ({ name: data.name, bio: data.bio }));
return res.send(JSON.stringify(out));

For error handling, you can wrap the Promise.all call in a try/catch block, and handle the rejected promise there.

Leave a Reply

(*) Required, Your email will not be published