我正在创建一个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,但我不确定如何使用它。
任何帮助将不胜感激,谢谢!
答案 0 :(得分:0)
你可以做这样的事情
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
中使用点差运算符希望这有帮助!
答案 1 :(得分:0)
您可以使用axios.all
方法解决所有承诺。以下是axios文档中的示例,这里是链接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
}));