如何才能发送一个快速响应,直到asynchronous循环完成后?

想要做下面的事情。 我认为这是asynchronous调用的问题,因为我发送的响应始终是一个空数组,但API正在返回数据。 相当新的这一点,任何input,非常感谢!

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