Using the jquery deferred object's then () solves the problem of multiple AJAX operation order dependencies

Source: Internet
Author: User

The previous article "Callback Hell for JavaScript Asynchronous Code" mentions 3 questions that are often encountered in writing Ajax code, and now we see how to use then () to solve the 2nd problem: if there is a dependency between AJAX requests, our code will form pyramid of Doom (Pyramid Doom). For example, we have to do one thing: There are 4 ajax access to the URL address, you need to first AJAX access to the 1th, after the 1th visit completed, with the returned data received as parameters to visit the 2nd, the 2nd access to complete after the 3rd ... This is done to 4 full access. In this way, it would seem like this:

$.ajax ({  
    url:url1,  
    success:function (data) {  
        $.ajax ({  
            url:url2,  
            data:data,  
            success: function (data) {  
                $.ajax ({  
                    //...});}}  
);

1.deferred.then () is the equivalent of Deferred.done (), Deferred.fail (), deferred.progress (), and can register 3 callback functions in the same state.
function success (data)
{
	alert ("Success data =" + data);
}

function fail (data)
{
	alert ("Fail data =" + data);
}

function progress (data)
{
	alert ("Progress data =" + data);
}

var deferred = $. Deferred ();

Register with callback
Deferred.then (success, fail, progress);

Register callback
Deferred.done (success) separately;
Deferred.fail (fail);
Deferred.progress (progress);

Deferred.notify ("10%");
Deferred.resolve ("OK");  
We can, of course, call the then () registration callback function multiple times as done (). Then () although it can be used in this way, but the actual development is not generally used, because there is no need. Before JQuery1.8, this is the role of the then () method.

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

var deferred = $. Deferred ();

Use then () to register a resolved state callback function and return a filtered promise
//return filtered is not the original deferred or Promise object of
var filtered = Deferred.then (function (value) {
				alert ("Trigger deferred filter.value=" +value);//5 return
				value * 2;
			});

//Register callback function again with filtered promise			
Filtered.done (function (value) {
    alert ("Filtered value=" + value);//10
}) C10/>deferred.resolve (5);

We registered a callback function with the Deferred.then (), which has a value of 5, and then registers the callback function with filtered, the new promise, and the value in this callback function is 10 (The return result of the first callback function). Now let's look at the official jquery explanation for then:

These filter functions can return a new value of to is passed along to the promise ' s. Done () or. Fail () callbacks, or they CA n Return another observable object (Deferred, Promise, etc) which'll pass it resolved/rejected status and values to T He promise ' s callbacks. If the filter function used is null, or does not specified, the promise would be 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 corresponding state of the callback function. If we are using the done (), fail (), progress () registered callback function, then all the callback functions in a state are given the same parameters. But if we use the then () registration 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 same second function is the parameter of the third callback function. You can compare the following 2 pieces of code to experience the difference between done () and then.

var deferred = $. Deferred ();

The Done () return is still the original deferred object
var Done_ret = deferred.done (function (data) {
	alert ("Data=" +data);//5
	return 2 * data;
});
Alert (deferred = = Done_ret);//true

Done_ret.done (function (data) {
	alert ("Data=" +data);//5
})

; Deferred.resolve (5);


var deferred = $. Deferred ();

Then () returns a new Promise Object//then the
returned value of the registered callback function will be the parameter of this new promise
var Then_ret = deferred.then (function (data) {
	alert ("Data=" +data);//5 return
	2 * data;
})
; Alert (Then_ret = = deferred);//false

Then_ret.done (function (data) {
	alert ("Data=" +data);//10
})

; Deferred.resolve (5);

Similarly, Deferred.then can also implement callback function filtering for rejected and pending states.
var defer = $. Deferred ();
var filtered = Defer.then (null, function (value) {return
    value * 3;
  });
 
Defer.reject (6);

Filtered.fail (function (value) {
  alert (' value is (3*6 =): + value ';
});


The following code implements chain tasks to solve the problem of callback difficulties in asynchronous operations.

var defered = $. Deferred ();

var promise1 = Defered.then (function (data) {
	alert (data);//Return
	data+= "1";
});

var promise2 = Promise1.then (function (data) {
	alert (data);//1 return
	data+= "2";
});

var promise3 = Promise2.then (function (data) {
	alert (data);//12 return
	data+= "3";
});

Promise3.done (function (data) {
	alert (data);//123
});

Defered.resolve ("");

Precisely because of the then () feature, we can embed the above complex AJAX revision into the following form:

var promise1 = $.ajax (URL1);
var promise2 = Promise1.then (function (data) {return
	$.ajax (url2, {"Data": Data}
); var promise3 = Promise2.then (function (data) {return
	$.ajax (url3, {"Data": Data}
); Promise3.done (function (data) {
	//data retrieved from Url3
});


Related Article

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.