1. What is a deferred object
The deferred object is a deferred object, meaning that the function is deferred to a point before it starts executing, and there are two ways to change the execution state (success: Resolve and Failure: reject), corresponding to two execution callbacks (Success callback function: Done and failed callback function fail)
2.deferred Object Use Example
The AJAX approach is actually a deferred object.
1) Common AJAX operations
"Index.html"function () {alert ("Success"function () {Alert (" Error ");});
The Success,error function does not begin execution until the URL response is requested
2) New wording after version 1.5
$.ajax ("index.html"). Done (function () {alert ("Success");}). Fail (function () {alert ("error");}). Done (function () {alert ("Success2");});
The new notation is free to add multiple callback functions, executed in the order in which they were added.
3) Execute callback function for multiple Ajax
$.when ($.ajax ("index.html"), $.ajax ("addorder2.html")). Done (function () {alert ("Success");}). Fail (function () {alert ("error");})
Only two AJAX requests succeed before the done function is executed
4) Specify the callback function for the normal method
var wait=function() {var tasks=function() {alert ("execution complete! ");}; SetTimeout (tasks,;);}; $.when (Wait ()). Done (function() {alert ("Success");}). Fail (function() {alert ("error")});
Wait is not a deferred object, and after running it does not wait for the wait () function to execute the result before executing the callback function.
Add the deferred object with the following code example:
var dtd=$. Deferred (); var wait=function var tasks= function () {alert () execution is complete! ");d td.resolve ();}; SetTimeout (Tasks, 5000 return DTD;}; $.when (Wait (DTD)). Done ( function () {alert ("Success" );}). Fail ( function () {alert ("error")});
Where the argument in $.when () must be a deferred object,
Dtd.resolve (); Change execution status to success, call done callback function.
Dtd.reject (); Change execution state to fail, call the fail callback function.
5) Promise () method for deferred objects
In the example above, a global deferred object is defined and can be called to change the execution state function outside the deferred object wait.
After the deferred object calls the Promise () method, it can only execute the callback function (Done,fail) and cannot perform a state change function (Resolve,reject)
The code examples are as follows:
varwait=function(){varDtd=$. Deferred ();vartasks=function() {alert ("Execution is complete!" ");d td.resolve ();}; SetTimeout (Tasks,5000);returndtd.promise ();};varD=wait ();d. Resolve ();//Execution state Change function resolve does not play any role! $.when (d). Done (function() {Alert ("Success"));}). Fail (function() {Alert ("error")});
The deferred use of jquery is detailed