What is the difference between the Deferred object and its own promise object?

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?

+27
javascript jquery deferred
Nov 10 2018-11-11T00:
source share
3 answers

It creates a “sealed” copy of the pending value without the .resolve() and .reject() methods. From the documentation :

The deferred.promise() method allows an asynchronous function to prevent other code from interfering with the progress or state of its internal request.

Used when the value to be changed does not make sense. For example, when jQuery creates an AJAX request, it returns a promise object. Internally, this is a .resolve() value for the original Deferred object, which the user respects with the promise.

+23
Nov 10 2018-11-11T00:
source share

When using the “promise” of the “Deferred” object, observers (objects that are pending for an example) do not have direct access to the “Delayed” object itself, therefore they cannot call, for example, the “Allow” method of this Delayed one. This is a way to protect the original Deferred.

+2
Dec 18 '13 at 9:33
source share

With Deferred, you can control your set state.

When it comes to a promise, you can read the state and possibly attach a callback. get

0
Nov 12 '15 at 9:18
source share



All Articles