rj tubera rj tubera - 7 months ago 26
Javascript Question

Wait till all multiple asynchronous ajax call are completed

Hello I have multiple ajax call, what I wanted to do is to fire all of them asynchronously then wait till all of them are finished before processing the returned data. I tried using $.when but to no avail. Here is my code:

//form_identifier_list is my flag to get the multiple forms in my html page
function test(form_identifier_list){
var deffereds = [];

$.each(form_identifier_list, function(key,value){
var this_form = $(this).parents('.ajaxed_form');
deffereds.push( $.post($(this_form).attr("action"), $(this_form).serializeForm()) );
});

$.when.apply($, deffereds).done(function(){
//how to output response obj?? i tried console.log(data) to no avail
}).fail(function(){

}).always(function(){

});
}


I also noticed my ajax requests do not have reponse (which i verified on my browser).

Is there a way to make multiple ajax calls fire asynchronously and then wait till all of them are finished then access the data?

Thanks

Answer

In the jquery page on when, there is a section that says:

In the case where multiple Deferred objects are passed to jQuery.when(), the method returns the Promise from a new "master" Deferred object that tracks the aggregate state of all the Deferreds it has been passed.

Also there is this on the ajax page

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface

So we can just assign the return value of the ajax to a variable and pass those variables into the .when.

To expand slightly on the example given on the .when page and integrate any number of ajax calls, you can do something like this:

var ajaxes = [];
for(var i=0; i<10; i++) {
    ajaxes.push($.ajax('a.php', {data: {t: i}}));
}
$.when.apply($, ajaxes)
    .done(function(){
        for(var i=0;i<arguments.length; i++) {
            $('#output').append(arguments[i] + "<br>");
        };
    });

If you have a known number of ajax calls, it gets a little simpler...you can do something more like this:

var a1 = $.ajax(...);
var a2 = $.ajax(...);
var a3 = $.ajax(...);
$.when(a1,a2,a3).done(function(o1, o2, o3) {
  $('#output').append(o1).append(o2).append(o3);
});

The first example is basically doing the same thing.

Comments