想要做类似下面的事情。我假设这是异步调用的问题,因为我发送的响应总是一个空数组,但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);
})
答案 0 :(得分:5)
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));
})