Dynamic array for Promise.all () in Bluebird
I want to add promises to an array passed in Promise.all()
dynamically
var P = require('bluebird');
var firstPromise = P.resolve().then(function () {
console.log('1 completed');
});
var all = [firstPromise];
for (var i = 2; i < 5; i++) {
(function closure(i) {
setTimeout(function () {
all.push(P.delay(1000).then(function () {
console.log(i + ' completed');
}));
}, 0);
})(i);
}
P.all(all).then(function () {
console.log('finish');
});
Output
1 completed
finish
2 completed
3 completed
4 completed
I want to print finish after all my promises are resolved. I know I have the wrong code, but how can I rewrite it to solve my question?
+3
source to share
1 answer
You are adding promises after the call P.all
because of your setTimeout.
This is not how promises work. You have to push all promises before calling Promise.all
:
var all = [firstPromise];
for (var i = 2; i < 5; i++) {
(function closure(i) {
all.push(new P(function(resolve, reject) {
setTimeout(function() {
P.delay(1000).then(function () {
console.log(i + ' completed');
}).then(resolve).catch(reject);
}, 0);
}));
})(i);
}
P.all(all).then(function () {
console.log('finish');
});
0
source to share