In-depth parsing of the deferred Deferred.promise () method in jquery _jquery

Source: Internet
Author: User
Tags event listener instance method

Deferred.promise () and. Promise ()

The two API syntax is almost the same, but there is a big difference. Deferred.promise () is a method of deferred instance, and he returns a Deferred.promise instance. A Deferred.promise object can be understood as a view of a deferred object that contains only a set of methods for the deferred object, including: Done (), then (), Fail (), isresolved (), isrejected ( , always (), these methods can only observe a deferred state, and cannot change the internal state of deferred objects. This is ideal for encapsulation of APIs. For example, the holder of a deferred object can control the state of the deferred state (resolved or rejected) according to its own needs, but can return the deferred object of the Promise object to the other observer. Observers can only observe changes in state binding the corresponding callback function, but can not change the intrinsic state of the deferred object, thus playing a good isolation protection.

Deferred.promise ()

$ (function () { 
  // 
  var deferred = $. Deferred (); 
  var promise = Deferred.promise (); 
   
  var dosomething = function (Promise) { 
    Promise.done (function () { 
      alert (' deferred resolved. '); 
    }); 
   
  Deferred.resolve (); 
  DoSomething (Promise); 
}) 

Deferred.promise () can also accept an object parameter, at which point the incoming object is given a promise method and returned as the result.
Existing object 
var obj = { 
 hello:function (name) { 
  alert ("Hello" + name); 
 } 
}, 
//Create A Deferred 
defer = $. Deferred (); 
 
Set object as a Promise 
defer.promise (obj); 
 
Resolve the deferred 
defer.resolve ("John"); 
 
Use the object as a Promise 
obj.done (function (name) { 
 This.hello (name);//would alert "Hello John" 
} ). Hello ("Karl"); Would alert "Hello Karl" 

Deferred.promise () simply blocks other code from changing the state of the deferred object. It can be understood that the deferred promise object returned through the Deferred.promise () method is not resolve, reject, progress, Resolvewith, Rejectwith, PROGRESSWI Th these can change the state of the method, you can only use done, then, fail and other methods to add handler or Judge State.

Deferred.promise () does not change the state of the deferred object, nor does it guarantee that the current state is unchanged, it simply guarantees that you cannot change the deferred promise object returned by Deferred.promise () deferred The state of the object. If we return this place directly to the DTD, it can work, too. The done processing function will not be executed until dtd.resolve ().

Specifically in that blog example, if we change the code to the following form:

var DTD = $. Deferred (); Create a new Deferred object
var wait = function (DTD) {
  var tasks = function () {
    alert ("Execution completed!") ");
    Dtd.resolve (); Change the execution state of the deferred object
  };
  SetTimeout (tasks,5000);
  return DTD;
$.when ((DTD))
. Done (function () {alert ("Haha, success!"). "); })
. Fail (function () {alert ("Error!) "); });

The results of such execution are the same as those previously returned to Dtd.promise.

Where is the difference? If we change this piece of $.when code to this:

var d = Wait (DTD);
$.when (d)
. Done (function () {alert ("Haha, success!"). "); })
. Fail (function () {alert ("Error!) "); });
D.resolve ();

We'll find alert ("Haha, success!"). "will be executed immediately," completed "It takes 5 seconds to bounce out.

But if the wait function is finally return dtd.promise () here D.resolve () will have an error, because the Resolve () method does not exist for object D.

Similarly, if we change the code to:

var DTD = $. Deferred (); Create a new Deferred object
var wait = function (DTD) {
  var tasks = function () {   alert ("Execution completed!") ");
   Dtd.resolve ();   Change the execution state of the deferred object
};
SetTimeout (tasks,5000);
return Dtd.promise ();
};
Dtd.resolve ();
$.when ((DTD))
. Done (function () {alert ("Haha, success!"). "); })
. Fail (function () {alert ("Error!) "); });    

We can also find alert ("Haha, success!"). is executed immediately because the deferred object is resolve () before it is passed in, and the state is not changed once the deferred object has been resolve or reject.

Then we'll change the code of the $.wait to:

$.when ((DTD))
. Done (function () {alert ("Haha, success!"). "); })
. Fail (function () {alert ("Error!) "); });
Dtd.resolve ();

We will also find alert ("Haha, success!"). ”); is executed immediately, although the DTD has not been resolve while the wait (DTD) is executing, and the Wait method returns Dtd.promise (), but the original deferred object of the DTD is exposed, and we can change its state from the outside.

So, if we really don't want other code to change the state of the deferred object inside the wait method, then we should write this:

var wait = function () {
  var DTD = $. Deferred (); Create a new Deferred object
  var tasks = function () {
    alert (completed!) ");   Dtd.resolve ();   Change the execution state of the deferred object
};
SetTimeout (tasks,5000);
return Dtd.promise ();
};
$.when (Wait ())
. Done (function () {alert ("Haha, success!"). "); })
. Fail (function () {alert ("Error!) "); });

That is, do not expose deferred directly, and finally return to Deferred.promise (), so that other places can only add handler code.


. Promise ()

first of all, this is not a deferred instance method! This method is a method of the jquery instance. This method is used for a set of types of actions (for example, animations) to return a Promise object after all is complete for the event listener to listen for its state and perform the corresponding handler function.

The method accepts two optional parameters:. Promise ([Type,] [target])

Type: The style of the queue, and the default value is the animation of the Fx,fx, the jquery object.
TargetObject: To give the object of promise behavior,

These two parameters are optional. The first parameter (i) currently has no other value type found except FX. Therefore, it is generally used for animation monitoring, after the completion of the animation to do some operations.

Example: A Promise object with no animation effect returning directly to a resolved state

var div = $ ("<div/>"); 

Div.promise (). Done (function (arg1) { 
 //will be immediately triggered 
 alert (this = = div && arg1 = = div); 
}); 

Example: triggers the done () listener function after the animation effect is complete

<! DOCTYPE html> 
 
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.