Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
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);
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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);
});

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda