JQuery deferred object usage details-implement ajax linear request data, jquerydeferred

Source: Internet
Author: User

JQuery deferred object usage details-implement ajax linear request data, jquerydeferred

Recently, I encountered an ajax Data Request problem, that is, I want to request three different interfaces and then perform operations on the data after the request is complete, the main problem is that you do not know who returned the three requests first, or you cannot guarantee that the data has been returned during the operation, the first thing that can be done is to write the second ajax request in succes of the first ajax request, but we all know that the write efficiency will be very low, so we give up.

After a long review, I finally found the method. Use a deferred object.

JQuery is developed quickly. It has a major version every six months and a minor version every two months. Each version introduces some new features. What I want to introduce today is a new feature introduced from jQuery 1.5.0-the deferred object.

1. What is a deferred object?

Put simply, the deferred object is jQuery's callback function solution.In English, defer means "delay", so the deferred object means "delay" to a certain point in the future. It solves the problem of time-consuming operations, provides better control over those operations, and unified programming interfaces.

 

II. General writing

The traditional method of jQuery's ajax operations is as follows:

$. Ajax ({

Url: "test.html ",

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

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

});

$. After ajax () is completed, if jQuery of version 1.5.0 or earlier is used, the returned XHR object cannot be chained. If jQuery of version 1.5.0 or later is returned, the deferred object is returned, you can perform chained operations.

Iii. New Writing Method

$. Ajax ("test.html ")

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

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

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

4. Specify multiple callback functions for the same operation

A major benefit of the deferred object is that it allows you to add multiple callback functions freely.

The above code is used as an example. If I want to run another callback function after the ajax operation is successful, what should I do?

It's easy. Just add it to the back.

$. Ajax ("test.html ")

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

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

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

Multiple callback functions can be added, which are executed in the order of addition.

5. The next step is to solve the problem of the landlord. Specify callback functions for multiple operations

Another major benefit of the deferred object is that it allows you to specify a callback function for multiple events, which is not traditionally written.

  $. When ($. ajax ("test1.html"), $. ajax ("test2.html "))

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

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

This Code indicates that two operations are performed first $. ajax ("test1.html") and $. ajax ("test2.html"). If it succeeds, run the callback function specified by done (). If one fails or both, run the callback function specified by fail. Test1.html and test2.html are both requested. Therefore, linear request data is achieved.

6. Complete deferred example

The biggest advantage of the deferred object is that it extends this callback function interface from ajax operations to all operations. That is to say, any operation, whether ajax or local, asynchronous or synchronous, can use various methods of the deferred object to specify the callback function.

Var dtd = $. Deferred (); // create a new deferred object

Var wait = function (dtd ){

Var tasks = function (){

Alert ("execution completed! ");

      Dtd. resolve ();// Change the execution status of the deferred object "completed". Execute the done function immediately.

};

SetTimeout (tasks, 5000 );

    Return dtd. promise (); // you cannot directly return a dtd. You must return dtd. promise ();

};

  

$. When (wait (dtd ))

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

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

7. Notes

1. The $. when () parameter can only be a deferred object, so you need to create an object first.

2. The default execution status of $. when () is "completed", and the subsequent done () method is triggered immediately, thus the function of the callback function is lost. The purpose of dtd. promise () is to ensure that the current execution status is not changed by the user.

3. Do not forget to pass in the dtd parameter (deferred object) directly when calling wait after modification );

VIII. Summary: Method of the deferred object. If you are interested, take a look.

We have discussed several methods for the deferred object. The following is a summary:

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

(2) deferred. done () specifies the callback function when the operation is successful.

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

(4) When deferred. promise () does not have a parameter, the function is to keep the running state of the deferred object unchanged. When the parameter is accepted, the function is to deploy the deferred interface on the parameter object.

(5) deferred. resolve () manually changes the running status of the deferred object to "completed", and immediately triggers the done () method.

(6) $. when () specifies the callback function for multiple operations.

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

(7) deferred. then ()

Sometimes, you can combine done () and fail () to save trouble. This is the then () method.

$. When ($. ajax ("/main. php "))

  . Then (successFunc, failureFunc );

If then () has two parameters, 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, it is equivalent to done ().

(8) deferred. reject ()

This method is opposite to deferred. resolve (). After the call, the running status of the deferred object is changed to "failed", and the fail () method is triggered immediately.

(9) deferred. always ()

This method is also used to specify the callback function. Its function is to always execute whether deferred. resolve () or deferred. reject () is called.

$. Ajax ("test.html ")

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

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.