bluebird 中的 Promise.all() 是否等待迭代器?
Does Promise.all() in bluebird wait for the iterator?
下面的例子来自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) 是否保证 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");
});
});
是的,它会等待,假设 fs.writeFileAsync()
returns 一个承诺(我不知道这是来自哪个 fs 库,因为 NodeJS 没有 writeFileAsync()
方法).
for 循环是同步的,因此它必须在调用 Promise.all()
之前完成。它启动了一堆异步调用,但它立即用每次调用一个承诺填充 files
数组。
这些承诺将按照文件写入完成的任何顺序自行解决。此时,您的 all promise
将调用它的 .then()
方法。
下面的例子来自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) 是否保证 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");
});
});
是的,它会等待,假设 fs.writeFileAsync()
returns 一个承诺(我不知道这是来自哪个 fs 库,因为 NodeJS 没有 writeFileAsync()
方法).
for 循环是同步的,因此它必须在调用 Promise.all()
之前完成。它启动了一堆异步调用,但它立即用每次调用一个承诺填充 files
数组。
这些承诺将按照文件写入完成的任何顺序自行解决。此时,您的 all promise
将调用它的 .then()
方法。