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

222
Visualizações
How can I wait to send an express response until after async loop is finished?

Wanting to do something like below. I assume that it's an issue with the async call as the response that I send is always an empty array, but the API is returning data. Pretty new to this, any input is greatly appreciated!

app.get('/:id/starships', (req, res) => {
  let person = findPersonById(people, req.params.id)[0];
  let starshipUrls = person.starships;
  for(let i=0; i<starshipUrls.length; i++){
    axios.get(starshipUrls[i]).then(response => {
      starships.push(response.data);
    })
    .catch(err => console.log(err));
  }
  res.json(starships);
})
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

axios.get returns a promise. Use Promise.all to wait for multiple promises:

app.get('/:id/starships', (req, res) => {
  let person = findPersonById(people, req.params.id)[0];
  Promise.all(person.starships.map(url => axios.get(url)))
    .then(responses => res.json(responses.map(r => r.data)))
    .catch(err => console.log(err));
})
about 4 years ago · Santiago Trujillo 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