2017-07-13 103 views
2

我有一个问题,等待我的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 

}

+0

你使用的是angularjs吗? –

回答

1

代替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 transformedResults; 
    }) 
}); 

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

试试这个,

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与si多个例子。