Last Updated: February 25, 2016
·
662
· herschel666

Handle an indeterminate amount of deferred objects in jQuery

jQuery's jQuery.when-method is great when it comes to dealing with several deferred objects. But things get messy when there is an indeterminate amount of them. Imagine you have a list of URLs with varying length, you want to make an AJAX-request for each URL and you want to do something after all requests are sent.

So you could iterate over that list of URLs and make the requests, but you can't drop deferred objects into the jQuery.when-method successively. This is a fugly situation!

But there is a way to manage this. With the help of the .apply-method:

// First we need an array to store the deferred objects
var dfds = [];

// After that we iterate over the list of URLs
for ( var i = 0, len = urls.length; i < len; i += 1 ) {
    // Storing the deferred object returned by jQuery.get
    dfds.push($.get(urls[i]);
}

// Passing the dfds-array to jQuery.when
$.when.apply($, dfds).done( /* your callback goes here * )

That's all. Inside the callback-function all response objects from the requests are passed in as arguments. You could e. g. iterate over the arguments object and grab the async data.

I hope this tip helps you! If there are any questions left, drop a comment.