jQuery deferred object with nested ajax calls

Aesthete picture Aesthete · Sep 5, 2012 · Viewed 12k times · Source

I have a situation in which my ajax calls must perform in a particular order. I have used jQuery Deferred objects in other situations, but cannot seem to find a way to make this behave appropriately.

I have a function which performs a number of ajax requests in it's lifetime. Some of the requests will be performed during the success callback of other requests.

My question: is there a way to return all nested deferred objects to the original $.when call?

A simplified example would be:

function nestedAjax() {
    $.get("/", function(){
        console.log("First ajax done.");
        $.get("/", function(){
            console.log("Second ajax done.");
        });
    });
};

I am trying to have the nestedAjax function to use $.when() and $.done() like so:

$.when(nestedAjax()).done(function(){
    console.log("Complete");
});​

With the console output reading:

> First ajax done.
> Second ajax done.
> Complete.

I can return the first get to achieve this:

> First ajax done.
> Complete.
> Second ajax done.

But obviously this is not what I require. Any help would be appreciated.

Answer

DrColossos picture DrColossos · Sep 5, 2012

It's actually quite simple. Though all the AJAX calls are Deferred objects, I still use one for the method itself.

function nestedAjax() {
    var dfd = $.Deferred();
    $.get("/echo/json/", function(){
        console.log("First ajax done.");
        $.get("/echo/json/", function(){
             console.log("Second ajax done.");
            dfd.resolve();
        });
    });

    return dfd.promise();
};