Express Axios循环承诺并更新以前的Axios响应数据

Express Axios循环承诺并更新以前的Axios响应数据,express,axios,Express,Axios,为了更新第一个ajax调用的response.data,我如何等待所有承诺得到解决?(使用swapi.co api的示例) 一个简单的express。获取包装器。每艘/星际飞船都列出了飞行员资源(见里面的评论)。我想在我的包装器/api/starships中有完整的飞行员数据 app.get('/api/starships/', function(req, res){ axios.get('https://swapi.co/api/starships') .then(function(resp

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

一个简单的express。获取包装器。每艘/星际飞船都列出了飞行员资源(见里面的评论)。我想在我的包装器/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})
})
});

看起来差不多。但是你的
功能(星际飞船,i){…
不会自动等待你的承诺,它会在你眨眼之前放大每一页并在准备好之前发送响应

您需要做出一个
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);

});

简洁的语法是ty和double,这正是我所缺少的。