【问题标题】:Dynamic array for Promise.all() in BluebirdBluebird 中 Promise.all() 的动态数组
【发布时间】:2015-08-16 05:21:48
【问题描述】:

我想向传递给Promise.all()的数组动态添加承诺

var P = require('bluebird');

var firstPromise = P.resolve().then(function () {
  console.log('1 completed');
});

var all = [firstPromise];

for (var i = 2; i < 5; i++) {
  (function closure(i) {
    setTimeout(function () {
      all.push(P.delay(1000).then(function () {
        console.log(i + ' completed');
      }));
    }, 0);
  })(i);

}

P.all(all).then(function () {
  console.log('finish');
});

输出是

1 completed
finish
2 completed
3 completed
4 completed

我想在我的所有承诺都得到解决后打印完成。我知道我的代码不正确,但是如何重写它来解决我的问题?

【问题讨论】:

  • Promise.all 等待现有数组,.all 调用后您的数组会发生变化。
  • 是的,我注意到了,但我的问题是如何重写我的代码来解决动态变化
  • 简单地说 - 你的代码中不应该有 settimeout,你应该使用 API 转换回调以使用 Promise,然后链接并在链上添加 .all - 我可以添加一个如果您愿意,请回答解释这一点。

标签: javascript promise bluebird


【解决方案1】:

由于您的 setTimeout,您将在 P.all 调用之后添加承诺。

这不是承诺的工作方式。 你必须在调用Promise.all之前推送所有承诺:

var all = [firstPromise];

for (var i = 2; i < 5; i++) {
  (function closure(i) {
    all.push(new P(function(resolve, reject) {
      setTimeout(function() {
        P.delay(1000).then(function () {
          console.log(i + ' completed');
        }).then(resolve).catch(reject);
      }, 0);
    }));
  })(i);
}

P.all(all).then(function () {
  console.log('finish');
});

【讨论】:

    猜你喜欢
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2020-05-13
    相关资源
    最近更新 更多