[英]How can I wait to send an express response until after async loop is finished?
想要做下面的事情。 我假設這是異步調用的問題,因為我發送的響應始終是一個空數組,但是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);
})
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));
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.