【问题标题】:How can I wait to send an express response until after async loop is finished?如何等待异步循环完成后再发送快速响应?
【发布时间】:2017-09-14 19:49:39
【问题描述】:

想做下面的事情。我认为这是异步调用的问题,因为我发送的响应始终是一个空数组,但 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);
})

【问题讨论】:

    标签: javascript node.js express asynchronous axios


    【解决方案1】:

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

    【讨论】:

    • 啊,我以前从未见过 Promise.all。完美运行,非常感谢!
    猜你喜欢
    • 2013-03-22
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 2014-04-03
    • 2019-08-20
    相关资源
    最近更新 更多