Is the following how we chain multiple promises in jQuery (1.8 and later)?
foo()
.then(function() { return bar(); })
.then(function() { return wah(); })
.then(function() { return lah(); })
.then(function() { return haha(); });
where all foo(), bar(), wah(), lah(), haha() have to return a promise.
I think one note is that we have to use then() instead of done(), because if we use done(), then the second action to the last action will all be started after action 1 is done, instead of one by one.
An example: https://jsfiddle.net/jq9d3tw1/
changeStyle($("#message1"), { fontSize: "3em" }, 3000)
.then(function() { return changeStyle($("#message2"), { marginLeft: "100px" }, 2000) })
.then(function() { return changeStyle($("#message3"), { opacity: 0 }, 1000) });
where changeStyle() creates a deferred, gets the promise, performs some action and resolves the promise when done, and returns that promise:
function changeStyle(element, style, duration) {
var d = new $.Deferred(),
p = d.promise();
element.animate(style, duration, function() {
d.resolve();
});
return p;
}
For this particular use case, jQuery gives you functionality to do this type of thing out of the box using a queue. By default, the
fxqueue applies to animations, including built-in ones likefadeIn(),slideUp(), etc.In this case, the
donefunction triggers the effect on the next element once the current element's animation is complete.See my JSFiddle for an example