jQuery 1.9+ .Ajax() New Promise Interface Advantages

Following on from 5 NEW JQUERY.AJAX() EXAMPLES JQUERY 1.9+, I wanted to document the changes (some could be classed as advantages) of using the promise interface for jQuery .Ajax() 1.9+.

  • Naming – Obviously the names have changed from success -> done, error -> fail, complete -> always.
  • Deferred – The deferred promises can be bound to anywhere in your application allowing flexibility and reusability.
  • Order of callbacks – They are called in this order: 1 fail, 2 done, 3 always. Standard.
  • Mutiples – You can specify any number of callbacks of the same type. ie .always(), .always(), .always() which will all get fired once the ajax request returns completes.
  • Arguments
  • Chaining – Since jQuery 1.8 you can chain ajax invocations using the .then() function. See below for example.
  • Combining – You can combine .done() and .error() into .then(). See below for example.
//old complete function
complete Function( jqXHR jqXHR, String textStatus )

//new done function
jqXHR.done(function(data, textStatus, jqXHR) {});

Source: jQuery.Ajax API

Feel free to leave comments if you find any more I’ve missed.

Combine .done() and .fail() into .then()

You can combine the done() and fail() functions in one then() function. The code above can be rewritten as:

var promise = $.ajax({
  url: "/myServerScript"});
 
promise.then(mySuccessFunction, myErrorFunction);

Source: Deferred and promise in jQuery

Chaining Ajax Requests

Since jQuery 1.8, you can chain the then() function sequentially. In the code below, first promise1 is run and when resolved successfully, getStuff is run, returning a promise and when this is resolved successfully, the anonymous function is executed.

var promise1 = $.ajax("/myServerScript1");
 
function getStuff() {
    return $.ajax("/myServerScript2");}
 
promise1.then(getStuff).then(function(myServerScript2Data){
  // Both promises are resolved});
Every callback function receives the result of the previous asynchronous function, in the case of Ajax, that would be the returned data.

Using .when() as promise

You can use .when() to allocate a promise callback function namely .done().

var container = $("#mycontainer");
$.when(
    function () {
        return $.Deferred(function (dfd) {
            container.fadeOut('slow', dfd.resolve);
        }).promise();
    }(),
    $.ajax({
        url: 'Path/To/My/Url/1',
        type: 'POST',
        dataType: 'json'
    }),
    $.ajax({
        url: 'Path/To/My/Url/2',
        type: 'POST',
        dataType: 'json'
    })
).done(function (x, data) {
    container.html('Your request has been processed!');
    container.fadeIn('slow');
});

As you can see we pass three promises to $.when, one for the fade out animation and two for the ajax operations.

* The first parameter is a self executing anonymous function that creates the deferred handler and returns the promise. In $.Deferred’s callback the dfd.resolve function is passed in to fadeOut()’s callback parameter, which means that once the animation completes the deferred will be resolved.
* With regards to the other two parameters we pass to $.when, since the result of $.ajax is a jqXHR object that implements Promise we just pass the value that’s returned as is.

Source: Always keep your (jQuery) Promises