返回前执行所有 axios 调用 JSON

Do all axios calls before returning JSON

我正在制作一个 API 服务器,在其中,我需要为负值调用在另一个 API 服务器上找到的转换方法。我相信我的代码是正确的,但由于 ASYNC,我相信它会在进行所有转换之前返回值。这是代码:

                     for(let i = 0; i < results.length; i++) { 
                        if (parseInt(results[i]['ACCOUNT_ID']) < 0) {
                          let account = axios.get('http://localhost:54545/api?request=convert&id='+results[i]['ACCOUNT_ID'])
                            .then(function (response) {
                              results[i]['ACCOUNT_ID'] = response.data.stringId;console.log(response.data.stringId);
                            })
                            .catch(function (error) {
                              console.log(error);
                            });
                        }
                      }

                      res.setHeader('Content-Type', 'application/json');
                      return res.status(200).json(results);

我想我需要以某种方式使用 Promise.all,但我不确定如何使用它。
如有任何帮助,我们将不胜感激,谢谢!

你可以这样做

let arrayOfPromises = [];
for(let i = 0; i < results.length; i++) { 
    if (parseInt(results[i]['ACCOUNT_ID']) < 0) {
        arrayOfPromises.push(axios.get('http://localhost:54545/api?request=convert&id='+results[i]['ACCOUNT_ID']));
     }
    }
    Promise.all(arrayOfPromises).then( (responses) =>  {
            ///do stuff here
        })
        .then( () => {
            res.setHeader('Content-Type', 'application/json');
        })
        .catch(function (error) {
            console.log(error);
        });
    
    
    return res.status(200).json(results);

So you are going to be pushing all of the axios async calls into an
array

Then Promise.all all of those async calls

.then of of that

You will then have an array of all of the axios calls, so you can do
whatever logic you are trying to do

then set the headers 

finally return

您还可以使用 Bluebird .spread 运算符 http://bluebirdjs.com/docs/api/spread.html 如果您知道传入内容的顺序。

你也可以在 ES6 中使用扩展运算符 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

希望这对您有所帮助!

您可以使用axios.all方法来解析所有的promise。这是取自 axios 文档的示例,这里是 link https://github.com/mzabriskie/axios

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
}));