I'm using the Bluebird Promise library in a node script and I'm having trouble understanding the order in which the code is executed.
I've got an array of Promises that I'm using the .each
method so they get executed in serially in order. In each of those promises I have two chained promises but the second promise is not executed in order that I'm expecting.
If we take the following code, I would have thought the output to be 0.0, 0.1, 0.2, 1.0, 1.1, 1.2
...etc. But this doesn't seem to the case. It's producing 0.0, 0.1, 1.0, 1.1, 0.2, 1.2
...etc.
function subPromise1(index)
{
return new Promise(function (resolve, reject) {
console.log(String(index) + ".1");
resolve(index);
});
}
function subPromise2(index)
{
return new Promise(function (resolve, reject) {
console.log(String(index) + ".2");
resolve(index);
});
}
var promiseArray = [];
for (var index = 0; index < 2; index++) {
promiseArray.push(new Promise(function (resolve, reject) {
console.log(String(index)+".0");
subPromise1(index).then(subPromise2).then(function (result) {
resolve(result);
});
}));
}
Promise.each(promiseArray, function (index) {
console.log("Completed " + index);
}).then(function (result) {
console.log(result);
process.exit(0);
});
I would have thought the main "each" promise would need to resolve before doing the next promise in the array? Any help in helping understand the issue would be much appreciated.