Using jQuery.when() to combine a jquery Deferred's promise and a jqXHR: why is the jqXHR's data wrapped in an array?

279 views Asked by At

See jsFiddle here: https://jsfiddle.net/dtds1n2t/2/¸

Here's the code from the jsFiddle:

var resultData = "result-data-string";

// Create a jQuery deferred
defA = $.Deferred();

// Make an ajax call, which creates a jqXHR object
defB = $.ajax({
  type: "POST",
  url: "/echo/json/",
  data: {
    json: JSON.stringify(resultData),
    delay: 1.5
  }
});

defA.done(function(data) {
  console.log("defA resolved");
  console.log(data);
  // data is resultData, as expected
});

defB.done(function(data) {
  console.log("defB resolved");
  console.log(data);
  // data is resultData, as expected
});


defAB = $.when(defA, defB);

defAB.done(function(aData, bData) {
  console.log("defAB resolved");
  console.log(aData);
  // aData is resultData, as expected
  console.log(bData);
  // bData is an array for some reason:
  // [ resultData, "success", jqXHR object? 
});

defA.resolve(resultData);

And here's the console output:

defA resolved
result-data-string
defB resolved
result-data-string
defAB resolved
result-data-string
["result-data-string", "success", Object]

Why is bData in the $.when().done callback part of an array??

My defA and defB can be either jqXHR objects from $.ajax() calls, or $.Deferred().promise() objects. I want the $.when().done callback to receive data in the same format, regardless of how the underlying promise/Deferred object was created!

0

There are 0 answers