Search code examples
javascriptnode.jsexpressasync-awaitfetch

How to wait for multiple fetch responses to be pushed in array before responding data back to client in (Node Express JS)


I am receiving the names of a few animals in query separated by commas. Now I have to call an API that only accepts one animal name at a time. I want to call the same API once for each animal and push the jsonified data in an array before I respond to my client.

I am getting an empty array on my client while testing and to my understanding, that is happening because the res.send() is executed while the promise is waiting to be resolved.

Any solution is greatly appreciated.

router.get('/animals', async (req, res) => {
  const mammalsArray = req.query.mammals.split(',');
  let final = [];
  await mammalsArray.forEach(async function(mammal) {
        const response = await fetch(`https://someapi.com/pedia?tag=${mammal}`);
        const json = await response.json();
        final.push(json);
      });
  res.send(final);
});

Solution

  • async function returns a promise. You want to save all the promises and when all the promises are resolved, you want to continue.

    You can wait for all the promises with Promise.all.

    I used map instead of forEach to map all array values to promises.

    router.get('/animals', async(req, res) => {
      const mammalsArray = req.query.mammals.split(',');
      let final = [];
      let promisesArray = mammalsArray.map(async function(mammal) {
        const response = await fetch(`https://someapi.com/pedia?tag=${mammal}`);
        const json = await response.json();
        final.push(json);
      });
      await Promise.all(promisesArray);
      res.send(final);
    });