The deferred object is the implementation of jquery's promises interface. It is a common interface for asynchronous operations, and can be seen as a waiting task for developers to set up through a number of interfaces. In fact, it acts as a proxy, wrapping those asynchronous operations into objects with some unifying features, typically AJAX operations, Web animations, web worker, and so on.
All of the Ajax operation functions of jquery, the default return is a deferred object.
What's promises?
Because of the JavaScript single-threaded nature, if an operation takes a long time, other operations must wait in line. In order to avoid the entire program from losing its response, the usual solution is to write the following actions in the form of "callback Functions" (callback). While this can solve the problem, there are some notable drawbacks:
1. The callback function is often written as a function parameter, which causes the input and output of the function to be very confusing and the readability of the whole program is poor;
2. Callback functions can often only specify one, and if you have multiple operations, you need to overwrite the callback function.
3. The operation of the entire process is disrupted, debug and debugging of the corresponding increase in the difficulty.
Promises is proposed to solve these problems, its main purpose is to replace the callback function, as an asynchronous operation of the solution. Its core idea is to have the asynchronous operation return an object, and all other operations are done against that object. For example, suppose the Ajax operation returns a Promise object.
Copy Code code as follows:
var promise = Get (' http://www.example.com ');
The Promise object then has a then method that can be used to specify the callback function. Once the asynchronous operation completes, the specified callback function is invoked.
Copy Code code as follows:
Promise.then (function (content) {
Console.log (content)
})
The above two pieces of code can be combined, so that the process of the program to see more clearly.
Copy Code code as follows:
Get (' http://www.example.com '). Then (function (content) {
Console.log (content)
})
Prior to version 1.7, jquery ajax operations used a callback function.
Copy Code code as follows:
$.ajax ({
URL: "/echo/json/",
Success:function (response)
{
Console.info (Response.name);
}
});
After version 1.7, AJAX operations return directly to the Promise object, which means that the callback function can be specified with the then method.
Copy Code code as follows:
$.ajax ({
URL: "/echo/json/",
}). Then (function (response) {
Console.info (Response.name);
});
Methods of deferred objects
$.deferred () method
The effect is to generate a deferred object.
Copy Code code as follows:
var deferred = $.deferred ();
Done () and fail ()
Both methods are used to bind the callback function. Done () specifies the callback function after a successful asynchronous operation, and fail () specifies the failed callback function.
Copy Code code as follows:
var deferred = $. Deferred ();
Deferred.done (function (value) {
alert (value);
});
They return the original deferred objects, so they can be chained and then linked to other methods (both done and fail).
Resolve () and reject ()
These two methods are used to change the state of the deferred object. Resolve () Changed state to asynchronous operation succeeded, reject () to operation failed.
Copy Code code as follows:
var deferred = $. Deferred ();
Deferred.done (function (value) {
alert (value);
});
Deferred.resolve ("Hello World");
Once resolve () is invoked, the callback functions specified by the done () and then () methods are executed sequentially, and once the Reject () is invoked, the callback functions specified by the fail () and then () methods are executed sequentially.
State method
This method is used to return the current state of the deferred object.
Copy Code code as follows:
var deferred = new $. Deferred ();
Deferred.state (); "Pending"
Deferred.resolve ();
Deferred.state (); "Resolved"
There are three return values for this method:
1.pending: The operation has not been completed yet.
2.resolved: Indicates successful operation.
3.rejected: Operation failed.
Notify () and Progress ()
Progress () is used to specify a callback function that is executed when the Notify () method is called. It is intended to provide an interface that allows you to perform certain actions, such as the progress of a regular return of a progress bar, during the execution of an asynchronous operation.
Copy Code code as follows:
var userprogress = $. Deferred ();
var $profileFields = $ ("input");
var totalfields = $profileFields. length
Userprogress.progress (function (filledfields) {
var pctcomplete = (filledfields/totalfields) *100;
$ ("#progress"). HTML (pctcomplete.tofixed (0));
});
Userprogress.done (function () {
$ ("#thanks"). HTML ("for completing Your profile!"). Show ();
});
$ ("input"). On (' Change ', function () {
var filledfields = $profileFields. Filter ("[value!= ']"). Length;
Userprogress.notify (Filledfields);
if (Filledfields = = Totalfields) {
Userprogress.resolve ();
}
});
Then ()
The function of then () is also to specify a callback function that can accept three parameters, or three callback functions. The first parameter is a callback function that is called when resolve, the second parameter is a callback function that is called when reject, and the third parameter is a callback function called by the Progress () method.
Copy Code code as follows:
Deferred.then (Donefilter [, Failfilter] [, Progressfilter])
Prior to jquery 1.8, then () was just. Done (). Fail () The grammatical sugars, the two are equivalent. After jquery 1.8, then () returns a new deferred object, and the Done () returns the original deferred object. If the callback function specified by then () has a return value, the return value is taken as an argument and passed in to the following callback function.
Copy Code code as follows:
var defer = jquery.deferred ();
Defer.done (function (a,b) {
return a * b;
). Done (function (result) {
Console.log ("result =" + result);
}). Then (function (A, b) {
return a * b;
). Done (function (result) {
Console.log ("result =" + result);
}). Then (function (A, b) {
return a * b;
). Done (function (result) {
Console.log ("result =" + result);
});
Defer.resolve (2, 3);
Before the jquery 1.8 version, the results of the above code were:
Copy Code code as follows:
result = 2
result = 2
result = 2
After the jquery 1.8 version, the return result is
Copy Code code as follows:
result = 2
result = 6
result = NaN
This needs special attention.
Copy Code code as follows:
$.ajax (URL1, {dataType: "JSON"})
. then (function (data) {
Return $.ajax (URL2, {data: {user:data.userId}});
). Done (function (data) {
Data obtained from the URL2
});
The last done method of the code above deals with the data obtained from the URL2, not the data obtained from the URL1.
Using then () modifies the return value feature, we can handle the value returned by the previous operation before invoking the other callback function.
Copy Code code as follows:
var post = $.post ("/echo/json/")
. then (function (p) {
return p.firstname;
});
Post.done (function (r) {Console.log (r);});
The code above uses the then () method to remove the required field (FirstName) from the returned data, so the following action can only be processed for this field.
Sometimes, an AJAX operation returns a JSON string that has an error property that indicates a failure. At this time, the traditional method can only be done by doing () to determine whether there are errors. The then () method enables the deferred object to invoke the Fail () method.
Copy Code code as follows:
var mydeferred = $.post ('/echo/json/', {json:JSON.stringify ({' Error ': true})})
. Then (function (response) {
if (response.error) {
Return $. Deferred (). Reject (response);
}
return response;
},function () {
Return $. Deferred (). Reject ({error:true});
}
);
Mydeferred.done (function (response) {
$ ("#status"). HTML ("success!");
}). Fail (function (response) {
$ ("#status"). HTML ("An error occurred");
});
Always ()
Always () is also the specified callback function, either resolve or reject.
Pipe method
The pipe method takes a function as a parameter that runs the callback function specified by the pipe method before calling the then method, the Done method, the Fail method, and the callback function specified by the Always method. It is typically used to perform preliminary processing of the data returned by the server.
Promise Objects
In most cases, we don't want the user to change the state of the deferred object from the outside. At this point, you can return a promise object for it based on the deferred object. We can think of the latter as a deferred-only version of the promise, or more commonly understood as promise as a commitment to the task to be accomplished.
You can add a callback function to the original deferred object by promise the object, query its state, but cannot change its state, meaning that the Promise object does not allow you to invoke resolve and reject methods.
Copy Code code as follows:
function Getpromise () {
Return $. Deferred (). Promise ();
}
try{
Getpromise (). Resolve ("a");
} catch (Err) {
Console.log (ERR);
}
The code above will be faulted, showing typeerror {}.
The Ajax () method of jquery Returns a Promise object. In addition, the animation class operation can also use the Promise object.
Copy Code code as follows:
var promise = $ (' Div.alert '). FadeIn (). Promise ();
$.when () method
$.when () accepts multiple deferred objects as parameters and then calls the callback function of the resolved state when all of them are successfully run, but calls the callback function of the rejected state as long as one of them fails. It is equivalent to merging multiple asynchronous operations into one.
Copy Code code as follows:
$.when (
$.ajax ("/main.php"),
$.ajax ("/modules.php"),
$.ajax ("/lists.php")
). Then (Successfunc, Failurefunc);
The code above indicates that the callback function specified by the then method will not be executed until three AJAX operations have ended.
When the method inside to do how many operations, the callback function has a number of parameters, corresponding to each of the previous operations return results.
Copy Code code as follows:
$.when (
$.ajax ("/main.php"),
$.ajax ("/modules.php"),
$.ajax ("/lists.php")
). Then (function (RESP1, RESP2, RESP3) {
Console.log (RESP1);
Console.log (RESP2);
Console.log (RESP3);
});
The callback function for the code above has three parameters, Resp1, resp2, and RESP3, which correspond to the results of the previous three Ajax operations.
Another effect of the When method is that if its argument returns a deferred or Promise object, then the callback function for the When method will run immediately.
Copy Code code as follows:
$.when ({testing:123}). Done (function (x) {
Console.log (x.testing); "123"
});
The callback function specified in the code above will run immediately after the When method.
With this feature, we can write an asynchronous operation function that has a caching effect. That is, the first time the function is called, the asynchronous operation is performed, and the function is called later, and the cached result is returned.
Copy Code code as follows:
function Maybeasync (num) {
var DFD = $. Deferred ();
if (num = = 1) {
settimeout (function () {
Dfd.resolve (num);
}, 100);
return Dfd.promise ();
}
return num;
}
$.when (Maybeasync (1)). Then (function (RESP) {
$ (' #target '). Append (' <p> ' + resp + ' </p> ');
});
$.when (Maybeasync (0)). Then (function (RESP) {
$ (' #target '). Append (' <p> ' + resp + ' </p> ');
});
The code above indicates that if the Maybeasync function has an argument of 1, an asynchronous operation is performed, otherwise the cached result is returned immediately.
Instance
Wait method
We can use the deferred object to write a wait method that indicates how many milliseconds are waiting before execution.
Copy Code code as follows:
$.wait = function (time) {
Return $. Deferred (function (DFD) {
SetTimeout (Dfd.resolve, time);
});
}
Use the following methods:
Copy Code code as follows:
$.wait (5000). Then (function () {
Alert ("Hello from the future!");
});
Rewriting the SetTimeout method
On the basis of the wait method above, you can also overwrite the SetTimeout method to return a deferred object.
Copy Code code as follows:
Function Dosomethinglater (FN, time) {
var DFD = $. Deferred ();
settimeout (function () {
Dfd.resolve (FN ());
}, Time | | 0);
return Dfd.promise ();
}
var promise = Dosomethinglater (function () {
Console.log (' already delayed execution ');
}, 100);
Custom actions using the deferred interface
We can use the deferred interface so that any operation can specify a callback function with the done () and fail ().
Copy Code code as follows:
Twitter = {
Search:function (query) {
var DFR = $. Deferred ();
$.ajax ({
URL: "Http://search.twitter.com/search.json",
Data:{q:query},
DataType: ' Jsonp ',
Success:dfr.resolve
});
return Dfr.promise ();
}
}
Use the following methods:
Copy Code code as follows:
Twitter.search (' Intridea '). Then (function (data) {
alert (Data.results[0].text);
});
Another advantage of the deferred object is that you can attach multiple callback functions.
Copy Code code as follows:
function DoSomething (ARG) {
var DFR = $. Deferred ();
settimeout (function () {
Dfr.reject ("Sorry, something went wrong.");
});
return DFR;
}
DoSomething ("Uh oh"). Done (function () {
Alert ("Won ' t happen, we ' re erroring here!");
}). Fail (function (message) {
Alert (Message)
});