等待每个内心的承诺完成 [英] Wait for forEach with a promise inside to finish

查看:39
本文介绍了等待每个内心的承诺完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在等待forEach循环完成时遇到问题,该循环内部有一个承诺.我找不到任何真正的解决方案,它将使脚本等到最后再继续执行.我无法使someFunction同步.

I have a problem with waiting for my forEach loop, which has a promise inside, to finish. I can't find any real solution, that would make the script wait till the end, before continuing with the execution. I cannot make the someFunction synchronous.

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
}

推荐答案

使用map()代替forEach()创建一个Promise数组,然后使用

Instead of forEach() use map() to create an array of promises and then use 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
})

这篇关于等待每个内心的承诺完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆