如果在完成循环中的最后一个承诺后如何解决此承诺?
var foo = function(JSONArray){
return new Promise(function(resolve,reject){
for(var i=0; i < JSONArray.length; i++){
doIntensiveWork(JSONArray[i])
.then(doMoreIntensiveWork) //returns a promise
}
//resolve() after every promise from the loop is fulfilled
})
}
我使用Bluebird
答案 0 :(得分:3)
使用bluebird。
var foo = function(array) {
return new Promise.map(array, function(element) {
return doIntensiveWork(element).then(doMoreIntensiveWork);
});
};
foo(['bar', 'baz'])
.then(function(returnedValues) {
// returnedValues is an array containing all values
// return by your intensive work in foo
});
答案 1 :(得分:0)
您可以使用Promise#each
:
var foo = function(jsonArray){
return Promise.each(jsonArray, doIntensiveWork).each(doMoreIntensiveWork);
});