简体   繁体   English

Bluebird Promises:内部带有 for 循环的链式 Promise 的顺序异步执行

[英]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.为了避免回调地狱,我链接了几个(Bluebird Promise)指令,每个指令都运行一个异步 for 循环。 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.而不是等待每个 for 循环完成,链直接冲到最后,在 for 循环仍在运行时显示“DONE”。 How can I change my for loops so that the promise chain "waits" for each one to finish before executing the next "then" section?如何更改我的 for 循环,以便 promise 链在执行下一个“then”部分之前“等待”每个循环完成?

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 .您不会返回由 promiseFor 创建的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(result2) {不会等待该代码完成。您需要在return 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)

  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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