It gets a bit trickier when you need to give a promise for the end of the whole task in order to decouple the code and not have to provide the callback when the request is initiated (which is the crux of Deferred):
You have to create a deferred to wait for the second ajax call and handle all the resolve and reject plumbery by hand... you can imagine how complex it could get with more and more chained requests.
With deferred.chain, here is how it would be coded:
It's much more direct and to the point and if you need to chain more, just add chain statements and you'll get the proper promise returned.
Just like when, chain can also deal with non-observable values, so it can be used to filter responses. This comes in handy when dealing with ajax requests in a when statement:
$.when( simpleAjax(...), simpleAjax(...) ).done(function( response1, response2) { // response1 and response2 are no longer arrays
// since the filtered promiseis just the actual
// ajax response, not the reponse with the jqXHR
// object and the statuslike a normal ajax call });
You can also use the filtering ability to deliver promises that are resolved with the data that is of interest to each part of the application:
var request = $.ajax( url, options ), status = request.chain(function( response ) { return response.status; }), data = request.chain(function( response ) { return response.data; }); status.done(function( responseStatus ) { // Deal with the status });
data.done(function( responseData ) { // Deal with the data });
This helps completely decouple portions of an app by hiding the actual data structure of the response from parts that don't need to know about it. It also helps refactoring: it's pretty easy now to change the logic into two separate ajax calls: