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 firstfail
function? As I understand,then
returns a$.Deferred.promise()
which is how the secondthen
function is chained (and executes). Thethen
doneFilter/function/callback in the first chain always returs(?) - so why/how does jQuery handle thefailFilter
differently? - Why does
then
return a$.Deferred.promise()
, yetdone
/always
/fail
, etc. return a$.Deferred
? What use would this be (and why does it differ tothen
)?