简体   繁体   中英

Bluebird Promises: sequential asynchronous execution of chained promises with for-loops inside

To avoid callback hell, I am chaining several (Bluebird Promise) instructions, each running an asynchronous for loop. Instead of waiting for each for loop to finish, the chain rushes right to the end where it shows "DONE" while the for loops are still running. How can I change my for loops so that the promise chain "waits" for each one to finish before executing the next "then" section?

return Object1.Asyncmethod1(param1)
  .then(function(result1) {

    var promiseFor = Promise.method(function(condition, action, value) {
      if (!condition(value)) return value;
      return action(value).then(promiseFor.bind(null, condition, action));
    });

    promiseFor(function(count) {
      return count < result1.length;
    }, function(count) {
      return Object.someOtherAsyncAction(someParam)
        .then(function(res) {
          return ++count;
        });
    }, 0)

  }).then(function(result2) {
    //another for loop just like the one above  
  }).then(function(result3) {
    console.log("DONE");
    res.json({
      result: result3
    });
  }).catch(function(err) {
    res.json({
      result: 'error:' + err
    });
  });

You do not return the Promise created by promiseFor . As of that, the chain is broken, and the .then(function(result2) { does not wait for that code to be finished. You need to add a return in front of the promiseFor(function(count) {

  .then(function(result1) {

    var promiseFor = Promise.method(function(condition, action, value) {
      if (!condition(value)) return value;
      return action(value).then(promiseFor.bind(null, condition, action));
    });

    return promiseFor(function(count) {
      return count < result1.length;
    }, function(count) {
      return Object.someOtherAsyncAction(someParam)
        .then(function(res) {
          return ++count;
        });
    }, 0)

  })

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