How do I chain three asynchronous calls using jQuery promises?

John Mcdock picture John Mcdock · Apr 16, 2013 · Viewed 95.6k times · Source

I have three HTTP calls that need I need to make in a synchronous manner and how do I pass data from one call to the other?

function first()
{
   ajax()
}

function second()
{
   ajax()
}

function third()
{
   ajax()
}


function main()
{
    first().then(second).then(third)
}

I tried to use the deferred for the two functions and I came up with a partial solution. Can I extend it to be for three functions?

function first() {
    var deferred = $.Deferred();
     $.ajax({

             "success": function (resp)
             {

                 deferred.resolve(resp);
             },

         });
    return deferred.promise();
}

function second(foo) {
     $.ajax({
            "success": function (resp)
            {
            },
            "error": function (resp)
            {
            }
        });
}


first().then(function(foo){second(foo)})

Answer

Beetroot-Beetroot picture Beetroot-Beetroot · Apr 16, 2013

In each case, return the jqXHR object returned by $.ajax().

These objects are Promise-compatible so can be chained with .then()/.done()/.fail()/.always().

.then() is the one you want in this case, exactly as in the question.

function first() {
   return $.ajax(...);
}

function second(data, textStatus, jqXHR) {
   return $.ajax(...);
}

function third(data, textStatus, jqXHR) {
   return $.ajax(...);
}

function main() {
    first().then(second).then(third);
}

Arguments data, textStatus and jqXHR arise from the $.ajax() call in the previous function, ie. first() feeds second() and second() feeds third().

DEMO (with $.when('foo') to deliver a fulfilled promise, in place of $.ajax(...)).