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;
}
This code can be even simpler if you are returning promise - you do not need to create anonimous function inside
https://jsfiddle.net/vadimb/jq9d3tw1/1/