Reputation: 143
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.
Upvotes: 1
Views: 189
Reputation: 3118
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/
Upvotes: 1