Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

229
Views
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);
})
over 4 years ago · Santiago Trujillo
1 answers
Answer question

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));
})
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!