I'm writing an app that at one point needs to get the result some number of requests before proceeding. This seems like a likely candidate for using JQuery's when
. eg:
// requests is an array of Deferreds
$.when.apply(null, requests).done(function(results) {
// process results
}
The catch is that the number of requests could be 1 or it could be more, and the when
function handles these cases differently. With only 1 request, the callback gets the standard (data, textStatus, jqXHR) arguments, however when multiple requests are supplied the callback receives a sequence of arguments: an array of (data, textStatus, jqXHR) values for each of the requests. Frustratingly, JQuery seems to be treating a singleton array of requests the same as a single argument request, meaning that this case must be handled differently.
The best I could come up with to tease these cases apart feels kinda clunky and took me a while to figure out due to the subtleties of the resultant arguments in the different cases, and then there's the rookie gotcha of the request array needing to be wrapped up in a function so that it can be accessed in the closure.
$.when.apply(null, function (){return requests;}()).done(function(results) {
if (requests.length == 1) {
processResults(results);
} else {
for (var i=0; i < arguments.length; i++)
processResults(arguments[i][0]);
}
moreStuff();
});
Is there a better or more elegant way than this?