Tuesday, 18 April 2017

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



via TigerBalm

No comments:

Post a Comment