简体   繁体   中英

Does Promise.all() in bluebird wait for the iterator?

In the case of the following example from 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");
});

Is it ensured by (bluebird) Promise that the for loop would finish before we start the Promise.all() line or are the for loops so fast that we can assume they will finish before Promise.all() line?

I'm trying to understand what I can expect to be finished in order, and what I need to wrap around Promise, so that I don't write something like this when unnecessary:

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

Yes, it will wait, assuming that fs.writeFileAsync() returns a promise (I can't tell which fs library this is from because NodeJS doesn't have a writeFileAsync() method).

The for loop is synchronous, so it must complete before the Promise.all() is called. It starts a bunch of asynchronous calls, but it immediately populates the files array with one promise per call.

Those promises will resolve themselves in whatever order the file writes complete. At which point, your all promise will call it's .then() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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