$ deferred object usage in detail

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.

The usual workaround is to assign them a callback function (callback). 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

The Ajax operation of jquery is traditionally written like this:

$.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 successful, run the callback function specified by done (), and if one fails or fails, execute the callback function specified by fail ().

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

However, there is a problem. The $.when () parameter can only be a deferred object, so wait must be overwritten:

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 ();

};

There are two places to be aware of.

First, the last line cannot return the DTD directly, and dtd.promise () must be returned. The reason is that jquery states that any one of the deferred objects has three execution states----incomplete, completed, and failed. If the default execution status of Dtd,$.when () is returned directly to "completed", the subsequent done () method is immediately triggered, which loses the function of the callback function. The purpose of dtd.promise () is to ensure that the current execution state----that is, "unfinished"----unchanged, so that the callback function is triggered only when the operation is complete.

Second, when the operation is completed, the execution state of the deferred object must be changed manually, otherwise the callback function cannot be triggered. The role of Dtd.resolve () is to trigger the done () method by turning the execution state of the DTD from "unfinished" to "completed".

Finally, remember that after you modify the wait, you must pass in the DTD parameter directly when you call.

$.when (Wait (DTD))

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

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

(Run code example 5)

Six, normal operation of the callback function interface (middle)

In addition to using $.when () to add a callback function for normal operations, you can also 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 6)

jquery rules, $. Deferred () can accept a function as an argument, and the function will be in $. Deferred () executes before returning the result. And, $. The Deferred object generated by Deferred () will be used as the default parameter for this function.

VII. callback function interface for normal operation (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 7)

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.

Viii. 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 are no parameters, the function is to keep the running state of the deferred object unchanged; 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) $.when () specifies a callback function for multiple operations.

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

(7) 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 ().

(8) Deferred.reject ()

This method, in contrast to Deferred.resolve (), triggers the Fail () method immediately after the call changes the running state of the deferred object to "failed".

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

$ deferred object usage in detail

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.