1

I have two ajax calls that executes some callback after both of them get completed using jQuery.when()

$.when(loadDataA(), loadDataB()).done(function(dataA, dataB) {
  console.log(xhr.status); // How do I get the xhr.status?
}

I want to know the xhr.status of the first call. With the normal .done() you can do something like:

.done(function(data, statusText, xhr) {
  console.log(xhr.status);
}

But I can not make it work in my case.

How do I get it when using jQuery.when?

dmferrari
  • 149
  • 12
  • if you have multiple xhr request you will need to have multiple stats – madalinivascu Feb 08 '17 at 13:09
  • I thought so. Do you have an example on how to do that? – dmferrari Feb 08 '17 at 13:13
  • if there's no built-in functionality for that (didn't find any), i would try to make loadDataA and B return an object that contains the xhr status with the data. You could then retreive it from dataA and dataB.. just an idea – Kaddath Feb 08 '17 at 13:20
  • 1
    `dataA` is an array with all passed parameters. `dataA[2]` is the `XMLHttpRequest` object ([fiddle](https://jsfiddle.net/3yjjhfh4/)) – Andreas Feb 08 '17 at 13:27
  • @Andreas yours is the answer. Thanks! – dmferrari Feb 08 '17 at 13:53

1 Answers1

1

From the documentation for $.when():

In the event a Deferred was resolved with no value, the corresponding doneCallback argument will be undefined. If a Deferred resolved to a single value, the corresponding argument will hold that value. In the case where a Deferred resolved to multiple values, the corresponding argument will be an array of those values. For example:

var d1 = $.Deferred();
var d2 = $.Deferred();
var d3 = $.Deferred();

$.when( d1, d2, d3 ).done(function ( v1, v2, v3 ) {
    console.log( v1 ); // v1 is undefined
    console.log( v2 ); // v2 is "abc"
    console.log( v3 ); // v3 is an array [ 1, 2, 3, 4, 5 ]
});

d1.resolve();
d2.resolve( "abc" );
d3.resolve( 1, 2, 3, 4, 5 );

In your case dataA will be an array with three elements:

dataA[0] -> data
dataA[1] -> statusText
dataA[2] -> xhr

With this...

How do I get it when using jQuery.when?

dataA[2].status

Andreas
  • 21,535
  • 7
  • 47
  • 56