I\'ve been reading about jQuery deferreds and promises and I can\'t see the difference between using .then()
& .done()
for successful callbacks
then()
always means it will be called in whatever case. But the parameters passing are different in different jQuery versions.
Prior to jQuery 1.8, then()
equals done().fail()
. And all of the callback functions share same parameters.
But as of jQuery 1.8, then()
returns a new promise, and if it has return a value, it will be passed into the next callback function.
Let's see the following example:
var defer = jQuery.Deferred();
defer.done(function(a, b){
return a + b;
}).done(function( result ) {
console.log("result = " + result);
}).then(function( a, b ) {
return a + b;
}).done(function( result ) {
console.log("result = " + result);
}).then(function( a, b ) {
return a + b;
}).done(function( result ) {
console.log("result = " + result);
});
defer.resolve( 3, 4 );
Prior to jQuery 1.8, the answer should be
result = 3
result = 3
result = 3
All result
takes 3. And then()
function always passes the same deferred object to the next function.
But as of jQuery 1.8, the result should be:
result = 3
result = 7
result = NaN
Because the first then()
function returns a new promise, and the value 7 (and this is the only parameter that will passed on)is passed to the next done()
, so the second done()
write result = 7
. The second then()
takes 7 as the value of a
and takes undefined
as the value of b
, so the second then()
returns a new promise with the parameter NaN, and the last done()
prints NaN as its result.