title: Better way to handle a variable number of deferred requests in a JQuery $.when call?
body: <p>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 <code>when</code>. eg:</p>
  
  <pre><code> // requests is an array of Deferreds
   $.when.apply(null, requests).done(function(results) {
       // process results
   }
  </code></pre>
  
  <p>The catch is that the number of requests could be 1 or it could be more, and the <code>when</code> 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. </p>
  
  <p>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. </p>
  
  <pre><code>$.when.apply(null, function (){return requests;}()).done(function(results) {
      if (requests.length == 1) {
          processResults(results);
      } else {
          for (var i=0; i &lt; arguments.length; i++)
              processResults(arguments[i][0]);
      }
     moreStuff();
  });
  </code></pre>
  
  <p>Is there a better or more elegant way than this?</p>