【发布时间】: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