我正在运行for循环并在for循环中调用REST API。假设userArray包含5个用户,那么API被调用一次,得到hello五次。那么如何在循环内运行API调用5次在节点js中
for(user in userArray){
var result=apiddetails.getuserdetails(user);
console.log(result);
console.log("hello");
}
答案 0 :(得分:0)
您可以尝试使用 async-await
for(user in userArray){
var result = (async function(){
return await apiddetails.getuserdetails(user);
})(user); //pass user as the argument
console.log(result);
console.log("hello");
}
答案 1 :(得分:0)
这是使用承诺的解决方案。
var promises = [];
for(user in userArray){
var promises.push[apiddetails.getuserdetails(user)]; //asumming you are returning promise from this function
}
Promise.all(promises).then(function(values) {
console.log(values);
});