等待每个承诺内部完成

时间:2017-07-13 13:27:01

标签: javascript

我有一个等待我的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
}

2 个答案:

答案 0 :(得分:15)

而不是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
})

答案 1 :(得分:2)

试试这个,

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上更多地参考此link