Javascript 在异步循环完成之前,如何等待发送快速响应?
想做下面的事情。我假设异步调用有问题,因为我发送的响应总是空数组,但API返回数据。非常新的,任何意见都非常感谢Javascript 在异步循环完成之前,如何等待发送快速响应?,javascript,node.js,express,asynchronous,axios,Javascript,Node.js,Express,Asynchronous,Axios,想做下面的事情。我假设异步调用有问题,因为我发送的响应总是空数组,但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++){ a
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);
})
app.get('/:id/starships',(req,res)=>{
let person=findPersonById(people,req.params.id)[0];
让StarshipURL=person.starships;
for(设i=0;i{
星际飞船。推送(响应。数据);
})
.catch(err=>console.log(err));
}
res.json(星际飞船);
})
axios.get
返回一个。用于等待多个承诺:
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));
})
啊,我以前从没见过Promise。非常好用,非常感谢!