Waiting on multiple asynchronous calls to complete before continuing Waiting on multiple asynchronous calls to complete before continuing jquery jquery

Waiting on multiple asynchronous calls to complete before continuing


You can use .ajaxStop() like this:

$(function() {  $(document).ajaxStop(function() {    $(this).unbind("ajaxStop"); //prevent running again when other calls finish    LoadContact();  });  LoadCategories($('#Category'));  LoadPositions($('#Position'));  LoadDepartments($('#Department'));});

This will run when all current requests are finished then unbind itself so it doesn't run if future ajax calls in the page execute. Also, make sure to put it before your ajax calls, so it gets bound early enough, it's more important with .ajaxStart(), but best practice to do it with both.


Expanding on Tom Lianza's answer, $.when() is now a much better way to accomplish this than using .ajaxStop().

The only caveat is that you need to be sure the asynchronous methods you need to wait on return a Deferred object. Luckily jQuery ajax calls already do this by default. So to implement the scenario from the question, the methods that need to be waited on would look something like this:

function LoadCategories(argument){    var deferred = $.ajax({       // ajax setup    }).then(function(response){        // optional callback to handle this response     });    return deferred;}

Then to call LoadContact() after all three ajax calls have returned and optionally executed their own individual callbacks:

// setting variables to emphasize that the functions must return deferred objectsvar deferred1 = LoadCategories($('#Category'));var deferred2 = LoadPositions($('#Position'));var deferred3 = LoadDepartments($('#Department'));$.when(deferred1, deferred2, deferred3).then(LoadContact);


If you're on Jquery 1.5 or later, I suspect the Deferred object is your best bet:http://api.jquery.com/category/deferred-object/

The helper method, when, is also quite nice:http://api.jquery.com/jQuery.when/