Let's create a simple Deferred object:
defer = $.Deferred( function ( defer ) {
setTimeout( defer.resolve, 3000 );
});
The above Deferred object will be in the "pending" state for 3 seconds, and then switch to the "resolved" state (at which point all the callbacks bound to it will be invoked).
Let's also retrieve the promise of that Deferred object:
promise = defer.promise();
Now, to add callbacks which are going to be invoked once the Deferred object is resolved, we can use .done()
or .then()
. However, we can invoke this method both on the Deferred object itself or its own promise object.
defer.then( handler );
or
promise.then( handler );
In both cases, the handler
function will be invoked (after 3 seconds in this case).
If we use $.when
, we can again pass the Deferred object itself or its promise object:
$.when( defer ).then( handler );
or
$.when( promise ).then( handler );
Again, there is no difference between the above two lines of code.
Live demo: http://jsfiddle.net/G6Ad6/
So, my question is since we can invoke .then()
, .done()
, etc. on the Deferred object itself and since we can pass that Deferred object into $.when()
, what's the point of .promise()
and retrieving the promise object? What's the purpose of the promise object? Why is there this redundancy in functionality?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…