0

I have following code:

var aReq = $.getJSON('/path/A'),
    bReq = $.getJSON('/path/B');

$.when(aReq, bReq).then(function(A, B) {
  console.log(A, B);
  // logs: [Array[5], "success", Object], [Array[20], "success", Object]
});

Why is this wrapped in a "jqXHR array"?

With a single $.getJSON this doesn't happen:

var aReq = $.getJSON('/path/A');
$.when(aReq).then(function(A) {
  console.log(A);
  // logs: [Object, Object, Object, Object, Object]
  // just like I wanted it in the first version
});

Is there a way to accomplish that the first version works? Maybe I understood something wrong with promises/deferred objects.

FWIW: I am using jQuery version 1.7.1 in this case.

UiUx
  • 967
  • 2
  • 14
  • 25
dan-lee
  • 14,365
  • 5
  • 52
  • 77

1 Answers1

2

This is well documented in the api as the intended behavior: http://api.jquery.com/jQuery.when/

If it wasn't returned in an array, how would it return different results for each passed in promise considering each passed in promise could have multiple arguments returned?

From the documentation:

If a single argument is passed to jQuery.when and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately. The doneCallbacks are passed the original argument. In this case any failCallbacks you might set are never called since the Deferred is never rejected.

In the case where multiple Deferred objects are passed to jQuery.when, the method returns the Promise from a new "master" Deferred object that tracks the aggregate state of all the Deferreds it has been passed. The method will resolve its master Deferred as soon as all the Deferreds resolve, or reject the master Deferred as soon as one of the Deferreds is rejected. If the master Deferred is resolved, it is passed the resolved values of all the Deferreds that were passed to jQuery.when. For example, when the Deferreds are jQuery.ajax() requests, the arguments will be the jqXHR objects for the requests, in the order they were given in the argument list.

Kevin B
  • 94,570
  • 16
  • 163
  • 180