I am trying to get my head around jQuery deferred/promises (using v1.8+).
From reading the documentation, a $.Deferred.then(...) method accepts a doneFilter and a failFilter as arguments to execute, and it returns a promise, which we can use to chain as follows:
function doDefer() {
var $defer = $.Deferred();
doSomethingAsynchronous(
function () {
$defer.resolve();
},
function () {
$defer.reject();
}
);
return $defer.promise();
}
doDefer()
.then(function () {
return;
}, function () {
// second `then` not called
})
.then(function (b) {
// `b` is undefined, since first `then` returned without a value.
}, function () {
// fail end
});
Two questions:
- Why does execution chain stop in
doDefer(), if it hits the firstfailfunction? As I understand,thenreturns a$.Deferred.promise()which is how the secondthenfunction is chained (and executes). ThethendoneFilter/function/callback in the first chain always returs(?) - so why/how does jQuery handle thefailFilterdifferently? - Why does
thenreturn a$.Deferred.promise(), yetdone/always/fail, etc. return a$.Deferred? What use would this be (and why does it differ tothen)?