【问题标题】:Wait for forEach with a promise inside to finish等待内部带有承诺的 forEach 完成
【发布时间】:2019-05-31 13:50:21
【问题描述】:

我在等待我的 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
}

【问题讨论】:

  • 你在用 angularjs 吗?

标签: javascript


【解决方案1】:

使用map() 代替forEach() 创建一个promise 数组,然后使用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
})

【讨论】:

  • 非常感谢您的回答,我也有同样的疑问,我不想处理包或复杂的事情。这是对这些情况的最佳回应,非常简单而精彩。再次,谢谢。问候
  • 简单明了的阅读+维护:感谢您的解决方案!
  • 如果我的函数没有返回任何东西,则不适合我
【解决方案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);
   });
}

您可以通过简单的示例参考此link 以了解有关Promise.all 的更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-17
    • 2018-03-05
    • 2016-10-16
    • 2015-04-24
    相关资源
    最近更新 更多