Axios looping promisses and update previous axios response data

Multi tool use
Axios looping promisses and update previous axios response data
How I can wait for all promises to be resolve in order to update the response.data of the first ajax call? (example using swapi.co api)
A simple express .get wrapper. Each /starship list the pilots resource (see comment inside). I want to have full pilots data in my wrapper /api/starships.
app.get('/api/starships/', function(req, res){
axios.get('https://swapi.co/api/starships')
.then(function(response){
// res.setHeader('Cache-Control', 'no-control');
// pilots: [
// "https://swapi.co/api/people/13/",
// "https://swapi.co/api/people/14/",
// "https://swapi.co/api/people/25/",
// "https://swapi.co/api/people/31/"
// ],
response.data.results.forEach(function(starship, i){
if (starship.pilots) {
var promises = ;
var fullpillots = ;
starship.pilots.forEach(function(pilot_info, i){
promises.push(axios.get(pilot_info))
})
axios.all(promises).then(function(results) {
var fullpillots_info = ;
results.forEach(function(value, i){
fullpillots_info.push(value.data)
})
// ??? how to update 1 response.data with fullpillots_info
starship.fullpillots_info = fullpillots_info;
});
} else {
console.log("No pilots")
}
});
res.json(response.data);
})
.catch(function(error){
console.log({"error": error})
})
});
1 Answer
1
It looks about right. But your function(starship, i){...
will not wait for your promises automatically, it will zoom through that forEach before your can blink and send the response before it's ready.
function(starship, i){...
You need to make a starshipPromises
and push in the promise from axios.all(...
.and then something along the lines of
starshipPromises
axios.all(...
axios
.all(starshipPromises)
.then((starhips)=>{
res.json(starships);
});
Here is a complete async/await version if that's an option:
app.get('/api/starships/', async function(req, res){
const starships = (await axios.get('https://swapi.co/api/starships')).data.results;
for (let starship of starships) {
starship.fullpillots_info = ;
for (let pilot of starship.pilots) {
starship.fullpillots_info.push( (await axios.get(pilot)).data );
}
}
res.json(starships);
});
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
ty and double ty for the clean syntax. It was exactly what I was missing.
– Stavros Anastasiadis
Jul 2 at 12:52