Use the then () of the jquery deferred object to solve the problem of multiple AJAX operation order dependencies

Source: Internet
Author: User

Original address: http://www.2cto.com/kf/201507/424202.html

Previous articles JavaScript async code callbacks in Hell refer to the 3 questions that are often encountered in writing Ajax code, and now we see how to use then () to solve question 2nd: if there is a dependency between AJAX requests, our code will form pyramid of Doom (Pyramid Doom). For example, we want to accomplish such a thing: There are 4 URL addresses for AJAX access, need to first AJAX access 1th, after the 1th access is completed, with the return data obtained as parameters and then access 2nd, 2nd after the completion of the visit 3rd ... With this to 4 all accesses complete. In this way, it seems to be the case:

1 $.ajax ({2 URL:URL1,3 success:function (data) {4 $.ajax ({5 Url:url2,6 Data:data,7 success:function (data) {8 $.ajax ({9                     //...  Ten                 });  One             }       A         });  -     }   -});

1.deferred.then () is equivalent to Deferred.done (), Deferred.fail (), deferred.progress (), and can register a callback function in 3 states at the same time.

1 function Success (data)2 {3Alert (Success data = +data);4 }5  6 function fail (data)7 {8Alert (Fail data = +data);9 }Ten   One function Progress (data) A { -Alert (Progress data = +data); - } the   - varDeferred = $. Deferred (); -   - //Registering callbacks together + Deferred.then (Success, fail, progress); -   + //registering callbacks separately A Deferred.done (success); at deferred.fail (fail); - deferred.progress (progress); -   -Deferred.notify (Ten%); -Deferred.resolve (OK);

Of course we can also call then () to register the callback function as done () many times. Then () Although this can be used, but the actual development is generally not so used, because there is no need. This is how the then () method works before JQuery1.8.

2.deferred.then () solves the problem of dependencies between multiple asynchronous operations, which is then () a really meaningful scenario. After JQuery1.8, then () replaces the obsolete pipe () method. In this scenario, we need to use Deferred.then () to return the new Promise object. The first way to use the above, we ignore the return value of Deferred.then ().

1 varDeferred = $. Deferred ();2  3 //use then () to register a resolved state callback function and return a filtered promise4 //The returned filtered is no longer the original deferred or Promise object.5 varFiltered =Deferred.then (function (value) {6Alert (trigger Deferred filter.value=+value);//57                 returnValue *2;8             });9  Ten //re-register the callback function with the filtered promise One Filtered.done (function (value) { AAlert (filtered value= + value);//Ten - }); -    theDeferred.resolve (5);

We use Deferred.then () to register a callback function in the completion state, the value of this callback function is 5, and then filtered the new promise register the callback function, the value of this callback function is 10 (The return result of the first callback function). Now let's look at the official jquery explanation:

These filter functions can return a new value to being passed along to the promise ' s. Do () or. Fail () callbacks, or they CA n Return another observable object (Deferred, Promise, etc) which'll pass its resolved/rejected status and values to T He promise ' s callbacks. If the filter function used is null, or not specified, the promise would be a resolved or rejected with the same values as th E original.

We know that deferred.resolve (), Deferred.reject (), deferred.notify () can specify parameter values, which are passed to the callback function in the appropriate state. If we are using the callback function registered by done (), fail (), Progress (), then all the callback functions in one state get the same parameters. But if we use then () to register the callback function, then the return value of the first callback function will be the parameter of the second callback function, and the return value of the second function is the parameter of the third callback function. You can compare the following 2 code to the difference between done () and then.

1 varDeferred = $. Deferred ();2  3 //Done () returned is still the original deferred object4 varDone_ret =Deferred.done (function (data) {5alert (data=+data);//56     return 2*data;7 });8Alert (deferred = = Done_ret);//true9  Ten Done_ret.done (function (data) { Onealert (data=+data);//5 A }); -   -Deferred.resolve (5);
1 varDeferred = $. Deferred ();2  3 //Then () returns a new Promise Object4 //then the return value of the registered callback function will be used as the parameter of this new promise5 varThen_ret =Deferred.then (function (data) {6alert (data=+data);//57     return 2*data;8 });9Alert (Then_ret = = deferred);//falseTen   One Then_ret.done (function (data) { Aalert (data=+data);//Ten - }); -   theDeferred.resolve (5);

Similarly, Deferred.then is able to implement callback function filtering for rejected and pending states

1 vardefer = $. Deferred ();2 varFiltered = Defer.then (NULL, function (value) {3     returnValue *3;4   });5   6Defer.reject (6 );7  8 Filtered.fail (function (value) {9Alert (Value is(3*6= ) -:  +value);Ten});

The following code can implement chain tasks to solve the problem of callbacks in asynchronous operations.

1 vardefered = $. Deferred ();2  3 varPromise1 =Defered.then (function (data) {4alert (data);//5     returndata+=1;6 });7  8 varPromise2 =Promise1.then (function (data) {9alert (data);//1Ten     returndata+=2; One }); A   - varPROMISE3 =Promise2.then (function (data) { -alert (data);// A the     returndata+=3; - }); -   - Promise3.done (function (data) { +alert (data);//123 - }); +   ADefered.resolve ();

Precisely because then () This feature, we can the above complex Ajax embedded revision into the following form:

1 varPromise1 =$.ajax (URL1);2 varPromise2 =Promise1.then (function (data) {3     return$.ajax (url2, {data:data});4 });5 varPROMISE3 =Promise2.then (function (data) {6     return$.ajax (url3, {data:data});7 });8 Promise3.done (function (data) {9     //data retrieved from Url3Ten});

Use the then () of the jquery deferred object to solve the problem of multiple AJAX operation order dependencies

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.