1

I just can't seem to get a handle on jQuery's $.Deferred handling of AJAX calls.

What I want to do is execute three AJAX calls, each of which performs some processing on the returned data. The success call of the third AJAX call requires that the processing from the first two calls be complete, but the order of the first two calls does not matter.

Here is my code, and a jsFiddle:

var firstAjax = $.getJSON('/echo/json/')
.done(
    function(data, textStatus, jqXHR){
        //do some initialization here based on the data
        alert(1);
        return jqXHR.promise();
    }
);

var secondAjax = $.getJSON('/echo/json/')
.done(
    function(data, textStatus, jqXHR){
        //do some initialization here based on the data
        alert(2);
        return jqXHR.promise();
    }
);

$.when(firstAjax, secondAjax)
.done(
    $.getJSON('/echo/json/')
    .done(
        function(data, textStatus, jqXHR){
            //do some initialization here that relies on the initialization of the first and second calls being complete
            alert(3);
        }
    )
);

Sometimes, but not always, "3" is alerted before "1" and "2". I have no problem with performing the third AJAX call immediately but its done handler needs to execute last.

1 Answer 1

1

you can do

var firstAjax = $.getJSON('/echo/json/').done(
function(data, textStatus, jqXHR){
    //do some initialization here based on the data
    alert(1);
    return jqXHR.promise();
}
);

var secondAjax = $.getJSON('/echo/json/')
.done(
function(data, textStatus, jqXHR){
    //do some initialization here based on the data
    alert(2);
    return jqXHR.promise();
}
);

$.when(firstAjax, secondAjax)
.done(function(){ 
 $.getJSON('/echo/json/')
.done(
    function(data, textStatus, jqXHR){
        //do some initialization here that relies on the initialization of the first and second calls being complete

  alert(3);
    }
)

});    

you miss the "function(){" on this line $.when(firstAjax, secondAjax).done(function(){
http://jsfiddle.net/ACBJs/1/

Sign up to request clarification or add additional context in comments.

1 Comment

Also, (a) it is not necessary to return jqXHR.promise(); from the done callbacks of firstAjax and secondAjax. A returned value/promise from a .done() callback has no downstream effect, unlike from a .then() callback. And (b) you shoud test this sort of thing with console.log(...) rather than alert(...), otherwise you may (in some circumstances) be adding your own finger speed into the chain of events.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.