Search code examples
jqueryajaxdeferred

Wait for AJAX requests inside a $.each using $.Deferred


I have a $.each cycle that fires an AJAX request.
What I want to do is wait until all AJAX requests are completed. I don't mind about the result of those AJAX requests, the matter is that I must be sure they are finished.
I think this can be done using $.Deferred, but I can't figure out how, even after have read the JQuery documentation.


Solution

  • To wait for all AJAX requests to finish you can store the jqXHR objects returned from the calls in an array. Then you can apply that array to $.when to be run when all request finish. Try this:

    var requests = yourDataStructure.map(function() {
      return $.ajax({
        // setup...
      });
    });
    
    $.when.apply($, requests).done(function() {
      console.log('All requests finished, do something here...');
    });