简体   繁体   中英

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.

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 eg:

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

instead of

.then(a=>b(a).then(b=>c))
var jsObj = ["1", "2", "3", "4", "5"]; // has 5 elements

for (var i = 0; i < jsObj.length; i++) {

   func1(jsObj[i]).then(function(returnVal1) {
        // finished func1
       func2(returnVal1).then(function(returnVal2) {
         // finished func2
          finalFn();
       });
    });
} // end of loop

// Now, I need to run the last function once the loop is complete
var count = 0;
function finalFn(){
  count++;
  if(count == jsObj.length){
     var data = ["1222"];
     func3(data, function() {
       alert("all done");
     });
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM