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?
A promise is a placeholder for a result which is initially unknown while a deferred represents the computation that results in the value. Every deferred has a promise which functions as a proxy for the future result.
A deferred object is an object that can create a promise and change its state to resolved or rejected . Deferreds are typically used if you write your own function and want to provide a promise to the calling code. You are the producer of the value. A promise is, as the name says, a promise about future value.
The defer attribute is a boolean attribute. If the defer attribute is set, it specifies that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing.
defer() to create a Promise. A Promise is a function that returns a single value or error in the future. So whenever you have some asynchronous process that should return a value or an error, you can use $q. defer() to create a new Promise.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With