A detailed description of the deferred object of jquery

Source: Internet
Author: User
Tags vcard

Nanyi

Date: August 16, 2011

The development of jquery is fast, with a small version of almost every half-yearly, every two months.

Each version introduces some new features. What I want to introduce today is a new feature introduced from the jquery 1.5.0 release----deferred object.

This feature is important and the future will be the core approach to jquery, which has revolutionized how Ajax is used in Jquery. To achieve this, all of Jquery's Ajax code has been Rewritten. however, It is more abstract, beginners are difficult to master, online tutorials are not many. so, I put my own study notes out, hope to be useful to EVERYONE.

This is not a Beginner's tutorial and is intended for developers who already have experience with Jquery. If you want to understand the basic use of jquery, read the jquery design ideas I wrote and the jquery best Practices.

======================================

A detailed description of the deferred object of jquery

Nanyi

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.

second, The Ajax operation of the Chain-style notation

first, look back at the traditional writing of Jquery's Ajax operations:

$.ajax ({

Url: "test.html",

Success:function () {
Alert ("haha, Success!") ");
},

Error:function () {
Alert ("error! ");
}

});

(run code Example 1)

In the above code, $.ajax () accepts an object parameter that contains two Methods: the success method specifies the callback function after the operation succeeds, and the error method specifies the callback function after the operation Failed.

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.

now, the new wording is this:

$.ajax ("test.html")

. Done (function () {alert ("haha, success! "); })

. Fail (function () {alert ("error! "); });

(run code Example 2)

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.html")

. Done (function () {alert ("haha, success! ");} )

. Fail (function () {alert ("error! "); } )

. Done (function () {alert ("second callback Function!) ");} );

(run code Example 3)

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

Iv. specifying callback functions for multiple operations

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! "); });

(run code Example 4)

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.

V. Normal operation callback function interface (upper)

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 Finished!") ");

};

SetTimeout (tasks,5000);

};

We specify a callback function for it, what should we do?

naturally, you will think that you can use $.when ():

$.when (wait ())

. Done (function () {alert ("haha, success! "); })

. Fail (function () {alert ("error! "); });

(run code Example 5)

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 Finished!") ");

Dtd.resolve (); Changing the execution state of a 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! "); });

(run code Example 6)

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

If you look closely, you will find in the wait () function above, There is another place I did not explain. So what is the role of Dtd.resolve ()?

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 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 (); Create a new Deferred object

var wait = function (dtd) {

var tasks = function () {

Alert ("execution Finished!") ");

Dtd.reject (); Changing the execution state of a deferred object

};

SetTimeout (tasks,5000);

Return dtd;

};

$.when (wait (DTD))

. Done (function () {alert ("haha, success! "); })

. Fail (function () {alert ("error! "); });

(run code Example 7)

Vii. 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 Finished!") ");

Dtd.resolve (); Changing the execution state of a deferred object

};

SetTimeout (tasks,5000);

Return dtd;

};

$.when (wait (DTD))

. Done (function () {alert ("haha, success! "); })

. Fail (function () {alert ("error! "); });

Dtd.resolve ();

(run code Example 8)

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 Finished!") ");

Dtd.resolve (); Changing the execution state of a 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.

(run code Example 9)

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, It is better to use the ALLENM to change 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 Finished!") ");

Dtd.resolve (); Changing the execution state of a deferred object

};

SetTimeout (tasks,5000);

return dtd.promise (); Returns the Promise Object

};

$.when (wait ())

. Done (function () {alert ("haha, success! "); })

. Fail (function () {alert ("error! "); });

(run code Example 10)

eight, normal operation callback function interface (middle)

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! "); });

(run code Example 11)

jquery rules, $. Deferred () can accept a function name (note, which is the name of the Letter) as a parameter, $. The Deferred object generated by Deferred () will be used as the default parameter for this Function.

nine, normal operation of the callback function interface (bottom)

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

var DTD = $. Deferred (); Generating deferred objects

var wait = function (dtd) {

var tasks = function () {

Alert ("execution Finished!") ");

Dtd.resolve (); Changing the execution state of a deferred object

};

SetTimeout (tasks,5000);

};

Dtd.promise (wait);

Wait.done (function () {alert ("haha, Success!") "); })

. Fail (function () {alert ("error! "); });

Wait (dtd);

(run code Example 12)

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.

X. Summary: Methods of 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 ().

(9) deferred.always ()

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

$.ajax ("test.html")

. Always (function () {alert ("executed! ");} );

(acknowledgements: after the first draft of this article was published, Allenm's letter stated that the original understanding of promise () was wrong. Now the second draft is revised according to his article, I would like to express my heartfelt thanks. )

Finish

A detailed description of the deferred object of jquery

Related Article

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.