【问题标题】:Does Promise.all() in bluebird wait for the iterator?蓝鸟中的 Promise.all() 是否等待迭代器?
【发布时间】:2016-09-11 11:30:19
【问题描述】:

下面的例子来自http://bluebirdjs.com/docs/api/promise.all.html

var files = [];
for (var i = 0; i < 100; ++i) {
    files.push(fs.writeFileAsync("file-" + i + ".txt", "", "utf-8"));
}
Promise.all(files).then(function() {
    console.log("all the files were created");
});

(bluebird) Promise 是否确保 for 循环在我们开始 Promise.all() 行之前完成,或者 for 循环如此之快以至于我们可以假设它们将在 Promise.all() 行之前完成?

我试图了解我可以期望按顺序完成什么,以及我需要围绕 Promise 包装什么,这样我就不会在不必要的时候写这样的东西:

some_promise_that_makes_files_array_with_for_loop().then(function(files){
    Promise.all(files).then(function() {
        console.log("all the files were created");
    });
});

【问题讨论】:

  • for 循环是同步的,因此 JavaScript 是单线程的可以保证它肯定会在下一行代码之前完成,不管那是什么。
  • 如果没有蓝鸟,这也是微不足道的 -> jsfiddle.net/dy3cmart

标签: javascript node.js promise bluebird


【解决方案1】:

是的,它会等待,假设 fs.writeFileAsync() 返回一个承诺(我不知道这是来自哪个 fs 库,因为 NodeJS 没有 writeFileAsync() 方法)。

for 循环是同步的,因此它必须在调用 Promise.all() 之前完成。它启动了一堆异步调用,但它会立即填充 files 数组,每次调用一个承诺。

这些承诺将按照文件写入完成的任何顺序自行解决。此时,您的all promise 将调用它的.then() 方法。

【讨论】:

  • Async 后缀看起来像是蓝鸟 Promsie.promisifyAll 的结果 - 所以它返回一个承诺是一个不错的选择
  • @JaromandaX 是的,这是 Bluebird 的一个功能。 All promisified functions receive the suffix Async.
  • @peteb - 实际上这并不完全正确 - 你可以set your own suffix
  • 好的,无论哪种方式,它都是 Bluebird 的事情,做一些承诺包装。很高兴知道,但我不确定是否应该专门将其添加到答案中。
  • 有没有什么规则或者列表可以找出哪些东西是同步运行的? IE。在哪里可以找到其中哪一个将同步运行:创建对象的新实例、设置对象的属性、对象的任何调用方法、需要 js 脚本。 (我们可以做什么样的测试来找到它?什么样的设置会创建一个测试环境来弄清楚什么是同步的?)
猜你喜欢
  • 2021-03-17
  • 2019-10-19
  • 2015-06-26
  • 2018-10-02
  • 1970-01-01
  • 2020-04-28
  • 2020-11-01
  • 2021-03-21
  • 2018-10-27
相关资源
最近更新 更多