The deferred of jquery

Source: Internet
Author: User
Tags readable

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 .

Simply put, the deferred object is the callback function solution for jquery. In English, defer means "delay", so the meaning of the deferred object is "delay" to some point in the future to execute.

It solves the problem of how to handle time-consuming operations, provides better control over those operations, and a unified programming interface. Its main function can be attributed to four points. Let's go through the sample code and learn it one step at a.

Take a look at the following code

function Step1 (callback) {    $.ajax ({        URL: '/api/test ',        type: ' POST ',        data: {            ...        },        Success:function (res) {            callback && callback ();}}    )}

When we use callbacks to solve real-world problems, it is easy to unknowingly appear in the code pyramid, the deeper the nesting level, the less readable code.

Step1 (function () {Step2 (function () {STEP3 (function () {STEP4 (function () {                step5 ()            })        })    })})

JS Library to implement the Promise mode, then our code will become clear and readable, and each step will wait for the previous step to complete before execution.

Chained notation for AJAX operations

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

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.

Let's look at a concrete example. Suppose there is a time-consuming operation, wait:

var wait = function () {var tasks = function () {alert ("Execution complete!    ");    };  SetTimeout (tasks,5000); };

However, by doing so, the done () method executes immediately, not the function of the callback function. The reason is that the $.when () parameter can only be a deferred object, so you must overwrite wait ():

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

The wait () function now returns the deferred object, which can be added as a chained operation.

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

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

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

To be clear about this problem, a new concept of "execution state" should be introduced. 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 Progress () method specifies the callback function (jQuery1.7 version 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 (); Create a new deferred object var wait = function (DTD) {var tasks = function () {alert ("Execution complete!      "); Dtd.reject ();    Change the execution state of the deferred object};    SetTimeout (tasks,5000);  return DTD;  }; $.when (Wait (DTD)). Done (function () {alert ("Haha, success! "); })  . Fail (function () {alert ("Error! "); });

Deferred.promise () method

There is still a problem with the above notation. That is, the DTD is a global object, so its execution state can change from the outside.

Take a look at the following code:

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

I added a line dtd.resolve () at the end of the code, which changed the execution state of the DTD object, causing the done () method to execute immediately, jumping out of "haha, success!" "The Prompt box, wait 5 seconds and then jump out" execution finished! "In the Prompt box.

To avoid this situation, 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.

Take a look at the following code:

var DTD = $. Deferred (); Create a new deferred object var wait = function (DTD) {var tasks = function () {alert ("Execution complete!      "); Dtd.resolve ();    Change the execution state of the deferred object};    SetTimeout (tasks,5000); return Dtd.promise ();  Returns the Promise object}; var d = Wait (DTD); Create a new D object and manipulate the object instead $.when (d). Done (function () {alert ("Haha, success! "); })  . Fail (function () {alert ("Error!  "); }); D.resolve (); At this point, the statement is invalid.

In the above code, the Wait () function returns the Promise object. We then bind the callback function above the object, not the original deferred object. The benefit is that you cannot change the execution state of the object, but you can only manipulate the original deferred object if you want to change the execution state.

However, a better method is to turn the DTD object into an internal object of the wait () function.

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

callback function interface for normal operation (medium)

Another way to prevent the execution state from being externally altered is to use the constructor $ for the deferred object. Deferred ().

At this point, the wait function remains the same, and we pass it directly to $. Deferred ():

$. Deferred (Wait). Done (function () {alert ("Haha, success! "); })  . Fail (function () {alert ("Error! "); });

In addition to the above two methods, we can also deploy the deferred interface directly on the wait object.

var DTD = $. Deferred (); Generate deferred object var wait = function (DTD) {var tasks = function () {alert ("Execution complete!      "); Dtd.resolve ();    Change the execution state of the deferred object};  SetTimeout (tasks,5000);  };  Dtd.promise (wait); Wait.done (function () {alert ("Haha, success!") "); })  . Fail (function () {alert ("Error!  "); }); Wait (DTD);

The key here is the dtd.promise (wait) line, which is the role of deploying the deferred interface on the wait object. Because of this line, you can call done () and fail () directly on wait.

Summary: Methods for deferred objects

There are several ways to deferred objects, and here's a summary:

(1) $. Deferred () generates a Deferred object.

(2) Deferred.done () Specifies the callback function when the operation succeeds

(3) deferred.fail () Specifies the callback function when the operation fails

(4) deferred.promise () when there is no parameter, a new deferred object is returned, and the running state of the object cannot be changed; When the parameter is accepted, the role is to deploy the deferred interface on the Parameter object.

(5) deferred.resolve () manually changes the running state of the deferred object to "completed", triggering the Done () method immediately.

(6)deferred.reject () This method is the opposite of Deferred.resolve (), which, after invocation, changes the running state of the deferred object to "failed", triggering the Fail () method immediately.

(7) $.when () specifies a callback function for multiple operations.

In addition to these methods, the deferred object has two important methods that are not covered in the tutorial above.

(8)Deferred.then ()

Sometimes to save time, you can write the done () and fail () together, and this is the then () method.

$.when ($.ajax ("/main.php" )). Then (Successfunc, Failurefunc);

If then () has two parameters, then the first parameter is the callback function of the Done () method, and the second parameter is the callback method of the Fail () method. If then () has only one parameter, then it is equivalent to done ().

Deferred.always ()

This method is also used to specify the callback function, which is the function, whether the call is Deferred.resolve () or Deferred.reject (), and finally always execute

$.ajax ("test.html"function() {alert ("Executed! ");} );

This article reproduced: http://www.ruanyifeng.com/blog/2011/08/a_detailed_explanation_of_jquery_deferred_object.html

If this article is helpful to you, you can give me a reward.

Technical Exchange QQ Group: 15129679

The deferred of jquery

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.