[英]Wait for forEach with a promise inside to finish
我在等待我的 forEach 循环(里面有一个承诺)完成时遇到了问题。 我找不到任何真正的解决方案,这会使脚本等到结束,然后再继续执行。 我无法使 someFunction 同步。
makeTree: function (arr) {
arr.forEach(function (resource) {
someModule.someFunction(resource).then(function () { //a Promise
//do something with the resource that has been modified with someFunction
});
});
// do something after the loop finishes
}
而不是forEach()
使用map()
创建一个承诺数组,然后使用Promise.all()
let promiseArr = arr.map(function (resource) {
// return the promise to array
return someModule.someFunction(resource).then(function (res) { //a Promise
//do something with the resource that has been modified with someFunction
return res;
})
});
Promise.all(promiseArr).then(function(resultsArray){
// do something after the loop finishes
}).catch(function(err){
// do something when any of the promises in array are rejected
})
尝试这个,
makeTree: function (arr) {
var promises = [];
arr.forEach(function(resource) {
promises.push(someModule.someFunction(resource));
});
Promise.all(promises).then(function(responses) {
// responses will come as array of them
// do something after everything finishes
}).catch(function(reason) {
// catch all the errors
console.log(reason);
});
}
您可以通过简单示例参考此链接以获取有关Promise.all
更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.