Deferred is the implementation of jquery's promise interface. He is a common interface for non-synchronous operations, and can be seen as completing a task before performing another task.
The Observer pattern is a pattern that is often used in development, which consists of two main parts: the subject and the viewer. With the observer pattern, the decoupling of the subject and the observer is achieved.
The topic is responsible for publishing content, while the observer receives the content published by the topic.
In JQuery, the implementation of the observer pattern is Deferred, and we look at its use first.
Using Deferred
//Defining ThemesvarSubject = (function(){ varDFD = $. Deferred (); varTask =function() { //Publish ContentDfd.resolve ("Alice"); } setTimeout (Task,3000); returndfd.promise ();}) ();//two observersvarFN1 =function(content) {Console.log ("FN1:" +content);}varFN2 =function(content) {Console.log ("FN2:" +content);}//Registered Observer$.when (subject). Done (FN1). Done (FN2);
In JQuery, you can even provide two topics to be observed at the same time, it should be noted that after two subjects are triggered, it will only really trigger, each observer get the two themes at a time, so the parameters become 2.
//Defining ThemesvarSubjectalice = (function(){ varDFD = $. Deferred (); varTask =function() { //Publish ContentDfd.resolve ("Alice"); } setTimeout (Task,3000); returndfd.promise ();}) ();varSubjecttom = (function(){ varDFD = $. Deferred (); varTask =function() { //Publish ContentDfd.resolve ("Tom"); } setTimeout (Task,1000); returndfd.promise ();}) ();//two observersvarFN1 =function(Content1, Content2) {Console.log ("FN1:" +content1); Console.log ("FN1:" +content2);}varFN2 =function(Content1, Content2) {Console.log ("FN2:" +content1); Console.log ("FN2:" +content2);}//Registered Observer$.when (Subjectalice, Subjecttom). Done (FN1). Done (FN2);
$.when () method
$.when () accepts multiple deferred objects as parameters, and when all of them run successfully, the callback function of the resolved state is called, but whenever one of them fails, the rejected state callback function is called. It is equivalent to merging multiple non-synchronous operations into one.
For example:
$.when ( "/main.php" ), "/modules.php" ), "/lists.php") ). Then ( Successfunc, Failurefunc);
The code above indicates that the callback function specified by the then method is not executed until the three Ajax operations have finished.
When the method executes how many operations, the callback function has the number of parameters, corresponding to each of the previous operations return results.
For example:
$.when ( "/main.php" ), "/modules.php" ), "/lists.php") ). Then ( function (RESP1, RESP2, resp3) { console.log (RESP1); Console.log (RESP2); Console.log (RESP3);});
The callback function for the above code has three parameters, Resp1, resp2, and RESP3, which in turn correspond to the results of the previous three Ajax operations.
Then () method
Then () is also the function of specifying a callback function, which can accept three parameters, that is, three callback functions. The first parameter is the callback function that is called when resolve, the second parameter is the callback function that is called when reject, and the third parameter is the callback function called by the Progress () method.
The code is as follows:
Deferred.then (Donefilter [, Failfilter] [, Progressfilter])
The difference between then () and done ()
After jquery 1.8, then () returns a new deferred object , and Done () returns the original deferred object .
If then () the callback function specified has a return value, the return value is passed as a parameter to the following callback function.
For example: The following code:
vardefer =jquery.deferred ();d Efer.done (function(A, b) {returnAb;}). Done (function(Result) {Console.log ("Result =" +result);}). Then (function(A, b) {returnAb;}). Done (function(Result) {Console.log ("Result =" +result);}). Then (function(A, b) {returnAb;}). Done (function(Result) {Console.log ("Result =" +( result);}); Defer.resolve (2, 3);
The returned result is:
result = 2
result = 6
result = NaN
Analysis:
1) The first result above is the output of the last done () of the first result, and the previous done return is not passed here, so result is the first parameter of resolve
2) The second result is the output of the second deferred, the input of the function with the first then, the second deferred is passed in, so the fifth done can accept the result of the 2*3.
3) The third result is the output of the third deferred, and when the second then executes, only a, no B (the last then executes when the A*B is returned, so the third then executes only a, not B), so result is Nan.
The comprehensive examples are as follows:
varRequestinfo =function() { vardefered = $. Deferred (); varurl = "Https://api.ffan.com/activity/v1/homepage/index"; $.ajax (URL, {dataType:"Jsonp", Jsonp:"Callback", timeout:5000, data: {type:"CityList"}}). Then (function(response) {if(Response && Response.data && response.data[0]) {defered.resolve (response.data[0].citylist); } }) returndefered.promise (); }
varCityinfo =function(Result) {varList = _.groupby (result,function(city) {returnCity.cityPinYin.charAt (0). toUpperCase (); }); _.each (list,function(City,key) {console.log (key); _.each (city,function(Item,index) {Console.log ("Item.cityid=" +Item.cityid); Console.log ("Item.cityname=" +item.cityname); }) }) //gets the Cityid of the first piece of data varcityid=list["A"][0].cityid;
return value for next then callreturn{Id:cityid}}
var info=function(result) { var id=result.id;//Previous then returned value Console.log ("cityid=" +ID); return true ; }
Call:
$.when (Requestinfo ()) . Then (cityinfo) . then (info);
Deferred use of jquery