Search code examples
javascriptjquerypromisebluebird

Chaining JavaScript promises in a loop - bluebird


I have been reading up on promises using bluebird and have been trying to achieve the following:

I need to run func1 and func2 till the loop is over. Once that's done, I would like to run func3. The code is as follows:

Note: All the functions have a callback function (to show that the operation has completed successfully)

var jsObj = ["1", "2", "3", "4", "5"]; // has 5 elements

for (var i = 0; i < jsObj.length; i++) {
var arr1 = [];
arr1 = jsObj[i];
func1(arr1).then(function(returnVal1) {
// finished func1
 func2(returnVal1).then(function(returnVal2) {
// finished func2
});
});
} // end of loop

// Now, I need to run the last function once the loop is complete
var data = ["1222"];
func3(data, function() {
alert("all done");
});

func1 and func2 are done using promises whereby the result is returned in the callback function variables returnVal1 and returnVal2. How can I chain/condense these three together so that one runs after the other in a loop and then runs func3 using just promises?

Cheers.


Solution

  • Map the data to promises, then use promise.all:

    var jsObj = ["1", "2", "3", "4", "5"]; // has 5 elements
    
    var promises = jsObj.map(function(obj){
     return func1(obj).then(function(value){
       return func2(value).then(function(val){
         return val;
       });
     });
    });
    
    Promise.all(promises).then(function(results){
     alert("all done");
    });
    

    You may also chain the promises e.g.:

    .then(a=>b(a)).then(b=>c)
    

    instead of

    .then(a=>b(a).then(b=>c))