我怎样才能等到异步循环完成后才发送明确的回复?
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
returns一个promise. Use Promise.all
等待多个promise:
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));
})
想做如下的事情。我认为这是异步调用的问题,因为我发送的响应始终是一个空数组,但 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
returns一个promise. Use Promise.all
等待多个promise:
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));
})