I'm trying to chain promises dynamically in order to deal with an unknown amount of asynchronous calls that need to happen in order. I'm using IO.JS/chrome which supports Promise's natively.
The creation of the promise fires immediately (at least relatively to console output). I was expecting to be able to collect promises then pass to Promise.all, but by that time they've already fired for reasons I don't understand.
Here's one method of chaining then, suggested by a comment on Dynamic Chaining in Javascript Promises
var lastPr = null;
console.log(" exit setup......................");
while(this.statesToExit.length > 0) {
var v = this.statesToExit.shift();
console.log("new Promise...");
var pr = new Promise(function (resolve, reject) {
console.log("doing Exit stuff at time " +curTime);
resolve(); //SOMETHING MORE SUBSTANTIAL GOES HERE
});
console.log("lastPr.then.");
if (lastPr != null) {
lastPr.then(pr);
}
lastPr = pr;
// console.log("adding pr to worklist");
// promiseList.push(pr);
// });
}
The other approach is
var promiseList= [];
console.log(" exit setup......................");
while(this.statesToExit.length > 0) {
var v = this.statesToExit.shift();
console.log("new Promise...");
var pr = new Promise(function (resolve, reject) {
console.log("doing Exit stuff at time " +curTime);
resolve(); //SOMETHING MORE SUBSTANTIAL GOES HERE
});
console.log("adding pr to worklist");
promiseList.push(pr);
});
}
console.log("Transition *START*-" +promiseList.length +" ");
Promise.all(promiseList).catch(function(error) {
console.log("Part of TransitionCursor Failed!", error);
}).then(this.summarizeWorkDone());
In both cases the output is like
new Promise...
doing Exit stuff at time 0
new Promise...
doing Exit stuff at time 0
"Transition *START*-"
vs the expected
new Promise...
new Promise...
"Transition *START*-"
doing Exit stuff at time 0
doing Exit stuff at time 0
How do I dynamically create a list of promises to later execute?