Jquery.deferred Object Use detailed _jquery

Source: Internet
Author: User
Tags readable

First, the preface
before jQuery1.5, if you need multiple AJAX operations, we typically use the following two ways:

1). Serial Invoke Ajax

$.ajax ({success:function () { 
  $.ajax ({success:function () {
    $.ajax.});}) 
;  

This way the code is poor readability, low efficiency, obscure, debugging and scheduling the complexity of the error is large.

2). Call Ajax in parallel

var promises = []; 
$.ajax ({
  success:function () { 
    Promises.push (' resolved '); 
    Check (); 
  } 
}); 
$.ajax ({ 
  success:function () { 
    Promises.push (' resolved '); 
    Check ();
  } 
}); 
$.ajax ({ 
  success:function () { 
    Promises.push (' resolved '); 
    Check (); 
  } 
}); 
var check = function () {//checks for all 3 values in the promises array}

This approach is pretty good for callbacks function calls, and it's good to get data in parallel. The disadvantage is that the code is lengthy, scalability is poor, debugging and scheduling the complexity of the error is high.

After jQuery1.5, the deferred object is added. So you can implement the same requirements as above in this way.

1) Promise

var address = $.ajax ({}); 
var tweets = $.ajax ({}); 
var Facebook = $.ajax ({}); 
Render_side_bar = function (address, tweets, Facebook) { 
  //render sidebar 
}
Render_no_side_bar = function () {}
$.when (address, tweets, Facebook). Then (Render_side_bar, Render_no_side_bar)

It can be seen that the code is readable, scalable, and greatly reduces the complexity of debugging and scheduling errors.

So the question is, what the hell is promises and deferred?

Second, detailed
2. What is a deferred object?
The deferred object, which is a deferred object, is a solution to the callback function introduced in the jquery version 1.5, representing some of the operations to be done, and provides a number of ways to help users use them.

The deferred object is the implementation of the promises interface. The JQuery 1.5 version and all subsequent Ajax return JQXHR objects are a deferred object.

Several great benefits of 2.deferred objects
2.1. Specify multiple callback functions for the same operation
One of the benefits of deferred objects is that it allows you to add multiple callback functions for an operation that is not possible in traditional Ajax.

$.ajax ("test.html")
. Done (function () {alert ("A-success callback!");}
. Fail (function () {alert (' There is a error! ');})
. Done (function () {alert ("second success callback!");});

2.2. Specify the same callback function for multiple operations
The benefit of the deferred object is that it allows you to specify the same callback function for multiple operations, which is not possible in traditional Ajax.

$.when ($.ajax ({}), $.ajax ({}))
. Done (function () {alert ("success!");})
. Fail (function () {alert ("error!");});

2.3. Non-Ajax Operation callback function
The benefit of the deferred object is that it no longer adheres to Ajax operations, that arbitrary operations (AJAX operations or local operations/asynchronous operations or synchronous operations) can use the deferred object to specify the callback function.

A very typical time consuming operation

var DFD = $. Deferred (); Create a deferred object
var wait = function (DTD) {
var tasks = function () {
alert ("over!");    
dtd.resolve ();//Change the state of the deferred object from pending to resolved
};
SetTimeout (tasks,50000);
return DTD;
};
$.when (Wait (DTD))
. Done (function () {alert ("success!");})
. Fail (function () {alert ("error!");});

2.4. Chained call
The traditional AJAX operations in jquery are this:

$.ajax ({
  URL: "",
success:function () {
alert ("success!");
},
error:function () {
Alert ("error!");
}
});

Where success specifies the callback function after the successful AJAX operation, and the error specifies the callback function after the Ajax operation failed. Before the jQuery1.5 version, the AJAX operation returned a XMLHttpRequest object that does not support chained operations. At the start of version 1.5, AJAX operations return the JQXHR object, which is a deferred object, and a significant benefit of the deferred object is that it can be chained because all methods of deferred object return are deferred objects.

Now the Ajax operation is written as follows:

$.ajax ({})
. Done (function () {alert ("success!");})
. Fail (function () {alert ("fail!");});

The comparison of two types of writing can be clearly seen, done () equivalent to the traditional Ajax operation of the Success method, fail () equivalent to the traditional AJAX operations fail method. Compared with the traditional writing, the code is more readable.

Methods of 3.deferred objects
3.1 Basic usage
(1). Generate deferred objects

var DFD = $. Deferred (); Create a deferred object
(2). Deferred the state of the object

There are three states of the deferred object

Pending: indicates that the operation is in an incomplete state and any deferred (deferred) object begins in the pending state.
Resolved: indicates successful operation.
rejected: indicates that the operation failed.
The state () method returns the current status of the deferred object.

$. Deferred (). State (); ' Pending '
$. Deferred (). Resolve (). State (); ' Resolved '
$. Deferred (). Reject (). State (); ' Rejected '

(3). Change the state of the deferred object

Invokes the Deferred.resolve () or deferred.resolvewith () conversion deferred (deferred) to the resolved (resolved) state and immediately executes any donecallbacks in the setting.

var callbackfunc = function () {Console.log (arguments[0]);}
var DFD = $. Deferred ();
Dfd.done (callbackfunc);
Dfd.resolve ("Hello"); ' Hello '

Invokes the Deferred.reject () or deferred.rejectwith () conversion deferred (deferred) to the rejected (deny) state and immediately executes any failcallbacks in the setting.

var callbackfunc = function () {Console.log (arguments[0]);}
var DFD = $. Deferred ();
Dfd.fail (callbackfunc);
Dfd.reject ("fail"); ' Fail '

(4). Binding callback function

The callback function is triggered when the deferred object state changes. Any callbacks that use Deferred.then (), Deferred.always (), Deferred.done (), or deferred.fail () are added to this object and are queued for execution.

Pending-->resolved, executes any donecallbacks (done () designation) in the setup, and the parameters are passed to Donecallbacks by resolved.
Pending-->rejected, executes any failcallbacks (fail () specified in the setting), and the parameters are passed to Failcallbacks by resolved.
Pending-->resolved/rejected, executes the callbacks specified by Always (), and the parameters are passed to callbacks by resolved.

var f1 = function () {Console.log ("Done");}, 
   F2 = function () {Console.log ("fail");}, 
   F3 = function () {Console.log ("Always");};

var DFD = $. Deferred ();
Dfd.done (F1). Fail (F2). Always (F3);

If
dfd.resolve ();//' Done ' always '
//if
dfd.reject ();//' Fail ' always '

If a callback of the attachment is executed immediately after the state change, you do not have to worry about when the deferred object will be resolved or rejected, because the arguments will be passed to callbacks whenever they are callback.

var fun1 = function () {Console.log (arguments[0]);},
  fun1 = function () {Console.log (arguments[0));
var DFD = $. Deferred ();
Dfd.done (FUN1);
Dfd.resolve ("Hello"); ' Hello '
dfd.done (fun2);//' Hello '

Methods of 3.2.deferred objects
(1) $. Deferred ([Beforestart])--Creates a Deferred object, which is a function, and is one that is called before the constructor.

var func = function () {Console.log ("Start");} 
var DFD = $. Deferred (func); ' Start ' Create a deferred object

(2) Deferred.done (Donecallbacks [, Donecallbacks])--Calls add handlers when deferred (deferred) objects are resolved.

Args: Accept one or more parameters, all of which can be a single function or array of functions, and donecallbacks be invoked when deferred (delay) objects are resolved. Callbacks are executed in the order they were added.

var func1 = function () {Console.log ("1");},
   func2 = function () {Console.log ("2");},
   func3 = function () { Console.log ("3");};
var DFD = $. Deferred ();
Dfd.done ([func1,func2],func3,[func2,func1]);
Dfd.resolve (); "1 2 3 2 1"

(3) Deferred.fail (Failcallbacks [, Failcallbacks])--Calls add handlers when deferred (delay) object is rejected.

Args: Accepts one or more parameters, all of which can be a single function or array of functions, and failcallbacks is invoked when deferred (delay) objects are rejected. Callbacks are executed in the order they were added.

var func1 = function () {Console.log ("1");},
   func2 = function () {Console.log ("2");},
   func3 = function () { Console.log ("3");};
var DFD = $. Deferred ();
Dfd.fail ([func1,func2],func3,[func2,func1]);
Dfd.reject (); "1 2 3 2 1"

(4) Deferred.resolve (args) and deferred.resolvewith (context [, args])--resolves the deferred (deferred) object, and according to the given args parameter ( Resolvewith a given context) to invoke any donecallbacks.

Parameters: Args-Type (object), an optional argument passed to the callback function (Donecallbacks),

Context-type (object), which is passed as the this object to the completion callback function (Donecallbacks).

var func = function (arg) {console.log (ARG);
$. Deferred (). Done (func). Resolve ("done!"); ' done! '
var func = function (arg1,arg2) {console.log (Arg1.name + ', ' + arg2);
$. Deferred (). Done (func). Resolve ({name: ' Lucy '}, ' How are you! '); ' Lucy,how are you! '

The difference between resolve and resolvewith is equal to the difference between fire and Firewith.

var func = function () {
  console.log (this.name + ', ' + arguments[0] + ' + arguments[1] + ' + arguments[2 ');
} ;
$. Deferred (). Done (func). Resolvewith ({name: "Lucy"}, ["How", "are", "you!"]); /' Lucy,how are you! '

(5) Deferred.reject (args) and deferred.rejectwith (context [, args])--rejects the deferred (deferred) object, and according to the given args parameter ( Rejectwith a given context) to invoke any failcallbacks.

Parameters: Args-Type (object), an optional argument passed to the callback function (Donecallbacks),

Context-type (object), which is passed as the this object to the completion callback function (Donecallbacks).

var func = function (arg) {console.log (ARG);
$. Deferred (). Fail (func). Reject ("error!"); ' error! '
var func = function (ctx,arg) {console.log (Ctx.name + ', ' + arg);
$. Deferred (). Fail (func). Reject ({name: ' Mark '}, ' What happend! '); ' Mark,what happend! '

The difference between reject and rejectwith is equal to the difference between fire and Firewith.

var func = function () {
  console.log (this.name + ', ' + arguments[0] + ' + arguments[1]);
$. Deferred (). Fail (func). Rejectwith ({name: "Mark"}, ["What", "happend!"]); ' Mark,what happend! '

(6) Deferred.promise ([target])-Returns the Promise (deferred) object of the deferred (delay).

parameter is optional, returns a Promise (commitment) object when there is no parameter, the Promise (Commitment) object exposes only those delay methods (then, done, fail, always,pipe, progress, state, and Promise), does not expose any delay methods used to change the state (resolve, Reject, Notify,resolvewith, Rejectwith, and Notifywith). Using promise (commitment) will prevent others from damaging the promise you make.

function AsyncEvent () {var DFD = jquery.deferred ();
    Resolve after a random interval settimeout (function () {dfd.resolve ("Hurray");

    }, Math.floor (+ math.random () * 2000));
    Reject after a random interval settimeout (function () {Dfd.reject ("sorry");

    }, Math.floor (+ math.random () * 2000));  Show a "working ..." message every Half-second settimeout (function working () {if (dfd.state () = = "Pending") {dfd.notify ("working ...)
           ");
        SetTimeout (working, 500);

      }, 1);
 Return the "Promise so caller can" t change the Deferred return dfd.promise ();
       }//Attach a done, fail, and progress handler for the AsyncEvent $.when (AsyncEvent ()). Then (function (status) {
    Alert (Status + ", things are going");
    The function (status) {alert (status + ", fail this time");
    The function (status) {alert (status);

 }
);

When there is a parameter, the event is bound to the parameter, and then the Parameter object is returned (the actual return is an extended promise (commitment) object).

var obj = {
  hello:function (name) {
    alert ("Hello" + name);
  }
},
//Create a Deferred
DFD = $. Deferred ();

Set object as a Promise
dfd.promise (obj);

Resolve the deferred
dfd.resolve ("John");

Use the object as a Promise
obj.done (function (name) {
   Obj.hello (name);//would alert "Hello John"
}). He Llo ("Karl");

(7) $.when (deferreds)--Provides a way to execute a callback function of one or more objects.

Parameters: Type (Deferred), one or more deferred objects, or normal JavaScript objects.

Parameter passes in a single deferred object, returning its promise object.

function func () {
  var DFD = $. Deferred ();
  settimeout (function () {
    dfd.resolve ("Hurry");
  };
  return Dfd.promise ();
};

$.when (func ()). Done (function (ARG) {
  alert (ARG);/*alert "Hurry" *
});

parameter is passed into a deferred and promise object, the parameter is treated as a deferred object (resolved), and any donecallbacks bound to the above will be executed immediately.

$.when ({name:123}). Done (
  function (ARG) {alert (arg.name),}/* alerts "123" * *
);

A Promise object that returns a resolved (resolved) state without parameters.

$.when (). State (); "Resolved"

The parameter is a multiple Deferred object that tracks all Deferreds aggregation states and returns a Promise object based on a new host Deferred (deferred) object. When all deferred objects are resolved (resolve), the host Deferred (delay) object resolves (resolved) the method, or when one of the deferred objects is rejected (rejected), the host The Deferred (deferred) object Reject (Rejects) the method.

var D1 = $. Deferred ();
var D2 = $. Deferred ();
 
$.when (D1, D2). Done (function (v1, v2) {
  console.log (v1);//"Fish"
  console.log (v2);//"Pizza"
}); 
   d1.resolve ("Fish");
D2.resolve ("Pizza");

(8) Deferred.then (Donefilter [, Failfilter] [, Progressfilter])--Calls add handlers when deferred (deferred) objects are resolved, rejected, or still in progress.

Parameters:

Donefilter-type (function), a function that is invoked when a deferred (deferred) object is resolved.
Failfilter-type (function), optional when a function is called when the deferred (delay) object is rejected.
Progressfilter-type (function), which is called when a deferred (deferred) object generates a progress notification.
In fact, the then method can be understood as, put the done (), fail (), progress () together to write.

var filterresolve = function () {
   var DFD = $. Deferred (),
     filtered = Dfd.then (function (value) {return value * 2;});
   Dfd.resolve (5);
   Filtered.done (function (value) {Console.log (value);});
Filterresolve (); ' Ten '

var defer = $. Deferred (),
   filtered = Defer.then (null, function (value) {return
     value * 3;
   });

Defer.reject (6);
Filtered.fail (function (value) {
   alert (' value is 3*6 = + value ';
});

(9) Deferred.always (Alwayscallbacks [, Alwayscallbacks])-Executes alwayscallbacks when deferred (deferred) object is resolved or rejected.

As the name suggests, Alwayscallbacks is invoked whenever the state of a deferred object changes (resolves or rejects).

(deferred.state)--Gets the current state of a deferred (deferred) object and does not accept any arguments.

$. Deferred (). State ();//"Pending"
The three states of the Deferre (deferred) object are described above, which is useful for debug, for example, to determine whether it is resolved before preparing to reject a deferred object.

(one) deferred.notify (args) and Deferred.notifywith ()

(a) deferred.progress ()

(a) Deferred.pipe ()

(a). Promise ()

() deferred.isrejected () and deferred.isresolved (), which were discarded from jquery 1.7, have been removed from the newer version of the JQuery class library, and the state () method can be used instead of the two methods.

() Deferred.pipe ()--is deprecated from jquery 1.8.

4. Under what circumstances are deferred objects and promises used?
It says a lot, so in what circumstances do we use deferred objects and promises objects?

(1) Complex animation

Do not know when the end of the animation, but must be at the end of the animation to do some action or to start other animations, in this case, if the other way, it can easily lead to poor code readability, especially with some other operations, such as rendering, form operation, etc. Now jquery will return a promise for your animated operation so that these animations can be chained.

(2) Processing queues

Copy Code code as follows:
Window.queue = $.when () $ (' #list '). On (' click ', Function () {window.queue = Window.queue.then (function () {//do the thing} ) } )

(3) The wait Promise

function Wait (ms) { 
  var deferred = $. Deferred (); 
  settimeout (function () {deferred.resolve ()}, MS);
  return Deferred.promise (); 
}

Wait (1500). Then (function () {
    //over 1500ms this'll be executed 
});

(4) Typical AJAX operations

$.when ($.ajax ({}), $.ajax ({}))
. Done (function () {alert ("success! ");})
. Fail (function () {alert ("error! "); });

(5) Some time-consuming circulation operation

The above is the entire content of this article, I hope to help you learn.

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.