3

Why is jQuery's deferred.when returning promises in the done callback, rather than their corresponding response data?

var data = {
    json: JSON.stringify({
        text: 'some text',
        array: [1, 2, 'three'],
        object: {
            par1: 'another text',
            par2: [3, 2, 'one'],
            par3: {}
        }
    }),
    delay: 3
};

var firstRequest =  $.ajax({
    url:'/echo/json/',
    data: data,
    type: 'POST'
});

var secondRequest =  $.ajax({
    url:'/echo/json/',
    data: data,
    type: 'POST'
});

$.when.apply($, [firstRequest, secondRequest]).done(function(data1, data2){
    console.log(data1); // returns array, I expect a response object
    console.log(data2); 
});

Both the documentation and various answers on SO, like this, implies that I should get the actual response objects, rather than arrays with [responseobject, textstatus, jqxhr].

http://jsfiddle.net/2h48mr78/

Community
  • 1
  • 1
Johan
  • 35,120
  • 54
  • 178
  • 293
  • 1
    Uh, read the [jQuery docs](https://api.jquery.com/jquery.when/) again. The example with the `$.ajax` calls explicitly explains that "*Each argument is an array with the following structure: [ data, statusText, jqXHR ]*" – Bergi May 25 '15 at 21:09
  • @Bergi Wops, sometimes you need two sets of eyes... – Johan May 26 '15 at 06:03

1 Answers1

4

You're getting the correct structure back, however the data1 and data2 arguments isn't the actual data itself. It's actually an array with three items, the data, statusText, jqXHR so your data is actually in data1[0] which will log out:

Object {text: "some text", array: Array[3], object: Object}

The documentation is a bit unclear but shows how it works in the Example section.

Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92