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