NodeJS在循环完成后解析promise

时间:2014-11-24 16:23:01

标签: javascript node.js promise bluebird

如果在完成循环中的最后一个承诺后如何解决此承诺?

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

2 个答案:

答案 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);
});