How to loop through Ajax Requests inside a JQuery When - Then statment?

It's possible to do what you're asking. HOWEVER, the server you are sending your requests to probably has a reason for the limit they enforce. As someone who works in web development and has seen first hand how annoying DDOS, scraping, and other abuses of APIs can be, I would suggest conforming to their limit.

That being said, here's how you can do it.

$.ajax actually returns a deferred object, so you can use that to your advantage. Also $.when can accept any number of deferred objects. Combining these two facts can solve your problem.

var deferreds = [];
$.each(groupedStats, function(index, stat){
    deferreds.push(
        // No success handler - don't want to trigger the deferred object
        $.ajax({
            url: '/some/url',
            data: {stat: stat},
            type: 'POST'
        })
    );
});
// Can't pass a literal array, so use apply.
$.when.apply($, deferreds).then(function(){
    // Do your success stuff
}).fail(function(){
    // Probably want to catch failure
}).always(function(){
    // Or use always if you want to do the same thing
    // whether the call succeeds or fails
});

Note that this is not a race condition. Although $.ajax is asynchronous, $.each is not, so your list of deferreds will be the total list before you get to $.when and $.then/$.fail/$.always will only be triggered once they all complete.

EDIT: I forgot to add the splitting by 5s, but this illustrates the general idea. You can probably figure out from here how to apply it to your problem. Incidentally, you could just use array.splice(0,5) to get the next 5 results from the array. .splice is safe to use; if the total number of elements is less than 5, it will just take all the remaining elements.


You can use Async.js libray. and try the each function.