Handle waiting multiple ajax requests

Nov 23, 2013 15:42 · 154 words · 1 minute read ajax deferred jquery when

The general way to handle multiple ajax requests, you can use the following code.

$.when(ajaxCall1, ajaxCall2, ...).done(function(result1, result2, ..) {
    // do something

ps:result1, result2, … are all array objects and the really data exists in the first element of each result array

However, this way can work only when you already know how many ajax calls.
How do you handle multiple unknown ajax calls?

Here, we need to use apply to invoke jQuery’s when function and use arguments to get the all results

  $.when.apply($, [ajaxCall1, ajaxCall2, ...]).done(function(){
    var results = arguments; // result1, result2, ....
    // do something

The code here will work the same as the first code example.
But we can collect all ajax calls into an array then pass this array into apply function as the second parameter, so we don’t care how many ajax calls anymore.


jQuery Deferred - waiting for multiple AJAX requests to finish