Since using $.Deferred
I\'ve run into this scenario a couple times: I have a list of values each of which yields a Deferred Object in some way and I want to execute
A more elegant way to write this example is with the array map function (or jQuery's $.map):
var urls = [ 'foo.com', 'bar.com', 'baz.com', 'qux.com' ];
var defers = urls.map( function( url) {
return $.ajax({
url: 'http://' + url
});
});
$.when.apply(window, defers).done(function(){
// Do Something
});
You could even roll your own "whenDone" and "fetchURL" functions:
Array.prototype.whenDone = function(callback){
return $.when.apply(window, this).done(callback);
}
function fetchURL(url){
return $.ajax({
url: 'http://' + url
});
}
var urls = [ 'foo.com', 'bar.com', 'baz.com', 'qux.com' ];
urls.map( fetchUrl ).whenDone(function(){
// Do Something
});