jquery's Deferred object

Source: Internet
Author: User
var wait = function (DTD) {
var DTD = $. Deferred (); Inside the function, create a new deferred object,
var tasks = function () {
alert ("Execution completed.")      ");
Dtd.resolve (New Date ());    Returns the current time when execution completes
;
SetTimeout (tasks,5000);
return Dtd.promise ();  Returns the Promise Object
};
$.when (Wait ())
. Do (function (time) {alert (finish: + times);})
. Fail (function () {alert ("error). "); });
first, what is the deferred object.

Usually for some of the more time-consuming JS operations, such as asynchronous operations (Ajax read Server data), there are synchronous operations (traversing a large array), they can not immediately get results. you can use callback functions that specify which functions should be called once they are finished.

the deferred object is a callback function solution for jquery. "Delay" to a later point in the future execution. it addresses how time-consuming problems are handled, provides better control over those operations, and a unified programming interface. The main function, boils down to four: The chain style of Ajax operation specifies multiple callback functions for the same operation specify a callback function for multiple operations common operation callback function interface Two, the chain type writing of Ajax operation

The traditional writing of jquery's Ajax operations:
    $.ajax ({
URL: "test.html",
success:function () {
alert ("Haha, successful.") ");
},
error:function () {
alert (" error). " ");
}
});

After the $.ajax () operation is completed, if you are using jquery that is less than 1.5.0, the xhr object is returned and you cannot perform a chain operation ; If the version is higher than 1.5.0, the deferred object is returned and can be chained .
Done () is equivalent to Success method, fail () is equivalent to the error method. With the chain style, the readability of the code is greatly improved.

New wording:
$.ajax ("test.html")
. Done (function () {alert ("Haha, successful.") ");})
. Fail (function () {alert ("error). "); });
three, specifying multiple callback functions for the same operation

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

The callback function can add as many as you want, and they are executed in the order of addition.
$.ajax ("test.html")
. Done (function () {alert ("Haha, successful.") ");})
. Fail (function () {alert ("error). ");})
. Done (function () {alert ("Second callback function. ");} );
Specify callback functions for multiple operations: $.when

another great benefit of the deferred object is that it allows you to specify a callback function for multiple events, which is not possible with traditional writing.

$.when ($.ajax ("test1.html"), $.ajax ("test2.html"))
. Done (function () {alert ("Haha, successful.") ");})
. Fail (function () {alert ("error). "); });

Execute the two actions $.ajax ("test1.html") and $.ajax ("test2.html") and, if all succeeds, run the callback function specified by the done (), and execute the callback function specified by fail () if one fails or fails. v. Common operation callback function interface (deferred object extends from Ajax operations to all operations)

The great 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 asynchronous or synchronous-can use various methods of the deferred object to specify the callback function.

var DTD = $. Deferred (); Creates a new deferred object
var wait = function (DTD) {
var tasks = function () {
alert ("Execution completed.")      ");
Dtd.resolve ();    Change the execution state of the deferred object
dtd.reject ();//Change the execution state of the deferred object
};
SetTimeout (tasks,5000);
return DTD;
};
$.when ((DTD))
. Done (function () {alert ("Haha, successful.") ");})
. Fail (function () {alert ("error). "); });

jquery stipulates 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;
Invokes the callback function specified by the fail () method if the execution state is "failed";
If the execution status is incomplete, continue to wait, or call the callback function specified by the progress () method (added by the jQuery1.7 version).

Query provides the deferred.promise () method. Its role is to return another deferred object on the original deferred object, which only opens methods unrelated to changing the execution state (such as the Done () method and the Fail () method), shielding the methods associated with changing the execution state (e.g. resolve () Method and The Reject () method) so that the execution state cannot be changed.

   var wait = function () {
var DTD = $. Deferred (); Inside the function, create a new deferred object,
var tasks = function () {
alert ("Execution completed.")      ");
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, successful.") ");})
. Fail (function () {alert ("error).  "); });
D.resolve (); At this point, the statement is invalid

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

$. Deferred (Wait)
. Done (function () {alert ("Haha, successful.") ");})
. Fail (function () {alert ("error). "); });

jquery stipulates that $. Deferred () can accept a function name (note, is the name of the functions) as an argument, $. The Deferred object generated by Deferred () will be the default argument for this function.

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 completed.")      ");
Dtd.resolve ();    Change the execution state of the deferred object
};
SetTimeout (tasks,5000);
};
Dtd.promise (wait); Deploy the deferred interface Wait.done on the Wait Object
(function () {alert ("Haha, successful.") ");})
. 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. It is because of this line that you can invoke the done () and fail () directly above the wait. Ii. Methods of deferred objects

(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) when Deferred.promise () has no parameters, a new deferred object is returned, the running state of the object cannot be changed, and when the parameter is accepted, the function is to deploy the deferred interface on the Parameter object.

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

(6) Deferred.reject () This method is just the opposite of Deferred.resolve (), which immediately triggers the fail () method by changing the running state of the deferred object to "failed" after the call.

(7) $.when () specifies a callback function for multiple operations .
In addition to these methods, the deferred object has two important methods, which are not covered in the tutorials above.

(8) Deferred.then ()
sometimes for the sake of convenience, you can put the done () and fail () together to write, 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, then it is equivalent to done ().

(9) Deferred.always ()
This method is also used to specify the callback function, and its function is to always execute regardless of whether the call is Deferred.resolve () or Deferred.reject ().

$.ajax ("test.html")
. Always (function () {alert ("executed."). ");} );

Reference Ruan One peak blog: http://www.ruanyifeng.com/blog/2011/08/a_detailed_explanation_of_jquery_deferred_object.html

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.