蓝鸟的Promise.all()是否等待迭代器?
以下示例来自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"); });
(蓝鸟)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"); }); });
是的,它会等待,假设fs.writeFileAsync()
返回一个承诺(我不能告诉哪个fs库,因为NodeJS没有writeFileAsync()
方法)。
for循环是同步的,所以它必须在Promise.all()
被调用之前完成。 它启动了一堆asynchronous调用,但是它立即用每次调用的一个承诺填充files
数组。
这些承诺将以文件写入完成的顺序自行解决。 在这一点上,你的all promise
将称之为.then()
方法。