AJAX Promises using Array

As it stands, I’m getting an Uncaught TypeError: Object [object Array] has no method 'done' error in console. Am I correct in thinking that I can’t use this method?

Not on arrays, yes. You can call this method only on Promise and Deferred objects, like the one produced by $.when.apply(this, responseArray)

… but I can’t seem to get the response that I need. Instead, what I get is [response, "success", response] where the first response is the correct return response for one of the AJAX calls and the last response is the actual call itself.

As stated in the docs for $.when, it resolves the result promise with multiple arguments – and when the input promises themselves did yield multiple values (such as $.ajax does), each argument is an arguments object of the respective promise resolution. You were only getting the first of them with response, but there are responseArray.length (letsSayTwo) arguments to the callback.

How should I go about getting the correct responses from both AJAX calls?

You want to extract the first item (response data) from each arguments object, so you can use map:

$.when.apply(this, responseArray).done(function() {
  var responses = $.map(arguments, function(args) { return args[0]; }),
      spit = someAnalysis(responses);
  console.log(spit);
}).fail(function(jqXHR, textStatus, errorThrown) {
  console.log('fail: '+textStatus);
});

Leave a Comment