jquery Deferred objects

Source: Internet
Author: User

First, what is the deferred object?

In the process of developing a website, we often encounter some long-time JavaScript operations. Where there are asynchronous operations (such as AJAX reading server data) and synchronous operations (such as traversing a large array), they are not immediately able to get results.

It is common practice to specify a callback function (callback) for them. That is, which functions should be called as soon as they run to completion.

However, in terms of callback functions, jquery has a very weak function. To change this, the jquery development team designed the deferred object.

Second, the Ajax operation of the chain-style notation

After the $.ajax () operation is complete, if you are using a jquery that is less than 1.5.0, you are returning the XHR object, you cannot do the chained operation, and if you are above the 1.5.0 version, the deferred object is returned, and you can chain-operate.

$.ajax ("Test.do"). Done (function() {Alert ("Execution succeeded! ");}). Fail (function() {Alert ("Execution failed! "); });

As you can see, done () is equivalent to the success method, and fail () is equivalent to the error method. After using chained notation, the readability of the code is greatly improved.

Iii. specifying multiple callback functions for the same operation

One of the great benefits of deferred objects is that it allows you to freely add multiple callback functions.

As an example of the above code, if the Ajax operation succeeds, in addition to the original callback function, I would like to run a callback function, how to do?

It's very simple, just add it to the back of the line.

$.ajax ("Test.do"). Done (function() {alert ("Haha, success!) ");}). Fail (function() {alert ("Error! ");}). Done (function () {alert ("the second callback function!) ");} );

The callback function can add any number of them, which are executed in the order in which they are added.

Another great benefit of the deferred object is that it allows you to specify a callback function for multiple events, which is not done in traditional notation.

Take a look at the following code, which uses a new method $.when ():

$.when ($.ajax ("test1.html"), $.ajax ("test2.html")). Done (function() {alert ("Haha, success!) ");}). Fail (function() {alert ("Error! "); });

This code means that you perform two operations $.ajax ("test1.html") and $.ajax ("test2.html"), and if all succeeds, run the callback function specified by done (); fail () if one fails or fails The specified callback function.

Five, normal operation callback function interface

The biggest advantage of the deferred object is that it extends this set of callback function interfaces from Ajax operations to all operations. That is, any operation----whether it is an AJAX operation or a local operation, whether it is an asynchronous operation or a synchronous operation----can use various methods of the deferred object to specify a callback function.

 var  DTD = $. Deferred (); //   var  wait = function   var  tasks = function   () {alert (" execution is complete!)      "); Dtd.resolve ();  //  change the execution state of the deferred object  };    SetTimeout (Tasks,  5000 return   DTD; };$.when (Wait (DTD)). Done ( function  () {alert ("Haha, success!) " function  () {alert ("Error! "); });

When the wait () function finishes running, the callback function specified by the done () method is automatically run.

Vi. Deferred.resolve () method and Deferred.reject () method

jquery states that the deferred object has three execution states----incomplete, completed, and failed. If the execution state is "completed" (resolved), the deferred object immediately invokes the callback function specified by the done () method, or the callback function specified by the fail () method if the execution state is "failed", or if the execution state is "not completed", continue waiting, or call the callback function specified by the progress () method (the jQuery1.7 version is added).

In the previous part of the Ajax operation, the deferred object automatically changes its execution state based on the returned results, but in the wait () function, the execution state must be manually specified by the programmer. Dtd.resolve () triggers the Done () method by changing the execution state of the DTD object from "unfinished" to "completed".

Similarly, there is a deferred.reject () method that triggers the Fail () method by changing the execution state of the DTD object from "unfinished" to "failed".

 var  DTD = $. Deferred (); //   var  wait = function   var  tasks = function   () {alert (" execution is complete!)      "); Dtd.reject ();  //  change the execution state of the deferred object  };    SetTimeout (Tasks,  5000 return   DTD;  }; $.when (Wait (DTD)). Done ( function  () {alert ("Haha, success!) " function  () {alert ("Error! "); });

jquery provides the Deferred.promise () method. It does this by returning another deferred object on the original deferred object, which only opens methods (such as the Done () method and the Fail () method) that are independent of the change execution state, masking methods related to changing the execution state (such as resolve () Method and The Reject () method) so that the execution state cannot be changed.

jquery Deferred objects

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.