2017-04-18 150 views
1

想做下面的事情。我認爲這是異步調用的問題,因爲我發送的響應始終是一個空數組,但API正在返回數據。對此很新,任何輸入都非常感謝!如何才能發送快速響應,直到完成異步循環之後?

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

回答

4

axios.get返回一個promise。使用Promise.all來等待多個承諾:

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

啊我從來沒有見過Promise.all之前。完美的作品,非常感謝! – TigerBalm

相關問題