Axios循环允许并更新以前的axios响应数据

时间:2018-07-02 09:09:08

标签: express axios

我如何等待所有的诺言都得到解决,以便更新第一个ajax调用的response.data? (使用swapi.co api的示例)

一个简单的Express .get包装器。每个/ starship都会列出飞行员资源(请参阅内部评论)。我想在包装器/ api / starships中获得完整的飞行员数据。

app.get('/api/starships/', function(req, res){
axios.get('https://swapi.co/api/starships')
 .then(function(response){
    // res.setHeader('Cache-Control', 'no-control');
    //  pilots: [
    //    "https://swapi.co/api/people/13/",
    //    "https://swapi.co/api/people/14/",
    //    "https://swapi.co/api/people/25/",
    //    "https://swapi.co/api/people/31/"
    // ],
    response.data.results.forEach(function(starship, i){
      if (starship.pilots) {
          var promises = [];
          var fullpillots = [];
          starship.pilots.forEach(function(pilot_info, i){
            promises.push(axios.get(pilot_info))
          })

          axios.all(promises).then(function(results) {
              var fullpillots_info = [];
              results.forEach(function(value, i){
                fullpillots_info.push(value.data)
              })
              // ??? how to update 1 response.data with  fullpillots_info
              starship.fullpillots_info = fullpillots_info;
          });
      } else {
          console.log("No pilots")
      }
    });

    res.json(response.data);
})
.catch(function(error){
  console.log({"error": error})
})
});

1 个答案:

答案 0 :(得分:1)

看起来不错。但是您的function(starship, i){...不会自动等待您的承诺,它会放大forEach,然后您才能眨眼并在准备好之前发送响应。

您需要制作一个starshipPromises并从axios.all(...提交诺言,然后按照

axios
  .all(starshipPromises)
  .then((starhips)=>{ 
     res.json(starships);
  }); 

如果可以的话,这里是完整的异步/等待版本:

app.get('/api/starships/', async function(req, res){

  const starships = (await axios.get('https://swapi.co/api/starships')).data.results;
  for (let starship of starships) {
    starship.fullpillots_info = [];
    for (let pilot of starship.pilots) {
      starship.fullpillots_info.push( (await axios.get(pilot)).data );
    }
  }
  res.json(starships);

});