Question

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?

Was it helpful?

Solution

It creates a "sealed" copy of the deferred 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 status of its internal request.

It's used when it doesn't make sense for the value to be modified. For example, when jQuery makes an AJAX request it returns a promise object. Internally it .resolve()s a value for the original Deferred object, which the user observes with the promise.

OTHER TIPS

When using the "promise" of a Deferred object the observers (objects waiting for resolve for exemple) dont have direct access to the Deferred object itself, so they can't call, for exemple, the method "Resolve" of that Deferred. It is a way of protecting the original Deferred.

With Deferred, you can control its state set.

When it comes to the Promise, you can read state and maybe attach callback. get

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top