2017-04-18 2 views
1

Ich möchte etwas wie unten tun. Ich nehme an, dass es ein Problem mit dem Async-Aufruf ist, da die Antwort, die ich sende, immer ein leeres Array ist, aber die API Daten zurückgibt. Ganz neu dazu, jeder Input wird sehr geschätzt!Wie kann ich warten, bis die Async-Schleife beendet ist, um eine Express-Antwort zu senden?

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

Antwort

4

axios.get gibt ein promise. Verwenden Sie Promise.all für mehrere Versprechen warten:

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

Ahh ich noch nie Promise.all gesehen hatte. Funktioniert perfekt, vielen Dank! – TigerBalm

Verwandte Themen