繁体   English   中英

蓝鸟中的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)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.writeFileAsync()因为NodeJS没有writeFileAsync()方法,所以我不能说这是哪个fs库)。

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

这些承诺将以文件写入完成的任何顺序解决自己。 在这一点上,您all promise都会将其称为.then()方法。

暂无
暂无

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

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