Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

javascript - What's the difference between a Deferred object and its own promise object?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...