When using jQuery promises sequentially, it is possible to chain them using then
repeatedly:
e.g.
promise = promise.then(someoperation());
which also works inside a loop (very handy).
I have similar scenario where I needed to know when multiple parallel operations were completed, but not go through the coding overhead (e.g. added complexity) of creating an array of promises for the sole purpose of calling $.when.apply
After looking at my options, I came up with this pattern as an alternative:
promise = $.when(promise, anotherpromise);
To test it I came up with this test:
var p = $.Deferred().resolve().promise();
[1,2,3,4,5,6,7,8,9,10].forEach(function(i){
p = $.when(p, delay(i,i * 500));
});
p.then(function(){
log("All done");
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/0rh8Lhv4/1/
Which appears to work just fine, so I started applying it to other example on StackOverflow.
The next one I tried with this pattern was to fix the example from Pass in an array of Deferreds to $.when():
My code:
$("a").click(function () {
var promise = GetSomeDeferredStuff();
promise.then(function () {
$("div").append("<p>All done!</p>");
});
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/ts1dqwe3/1/
Q. For some reason this one never fires the final event. Can anyone spot the problem?
Update
Based on a comment from @Karl-André Gagnon
, it seems the initial promise
can just be undefined and still work. Much simpler:
e.g.
var p;
[1,2,3,4,5,6,7,8,9,10].forEach(function(i){
p = $.when(p, delay(i,i * 500));
});
p.then(function(){
log("All done");
});