Let me create a simple deferred object:
defer = $.Deferred( function ( defer ) { setTimeout( defer.resolve, 3000 ); });
The above “Delayed” object will be in the “pending review” state for 3 seconds, and then switch to the “allowed” state (after which all calls related to it will be called).
Let also receive the promise of this object.
promise = defer.promise();
Now, to add callbacks that will be called after deleting the Deferred object, we can use .done() or .then() . However, we can call this method both for the deferred object object itself or its own promise object.
defer.then( handler );
or
promise.then( handler );
In both cases, the handler function will be called (after 3 seconds in this case).
If we use $.when , we can again pass the Deferred object or its promise object:
$.when( defer ).then( handler );
or
$.when( promise ).then( handler );
Again, there is no difference between the two lines of code above.
Live demo: http://jsfiddle.net/G6Ad6/
So my question is that we can call .then() , .done() , etc. in the deferred object itself, and since we can pass this deferred object to $.when() , what is the point of .promise() and extract the promise object? What is the purpose of the subject of the promise? Why is functionality redundant?
javascript jquery deferred
Šime Vidas Nov 10 2018-11-11T00: 00Z
source share