fildred13 fildred13 - 2 months ago 11
jQuery Question

How to get responses from $.when.apply($, deferreds)

How do I access the unknown number of responses from a

$.when.apply($, deferreds)
?

Hopefully the below attempt illustrates what I am trying to achieve:

var ajax1 = someAjaxFunction();

deferreds = [ajax1, ajax2, ... ajaxN];
responses = [ajax1Response, ajax2Response, ... ajaxNResponse];

$.when.apply($, deferreds).then(deferredsAllDone.apply(responses));


I need to be able to access the responses in
deferredsAllDone()
, and I also need to be able to distinguish which response came from which call. How do I accomplish that?

Answer

Maybe this will help. You need to iterate the arguments where each argument is an array of [responseData, statusText, xhrObj]

  var deferreds =[];
  for (var i=0; i<6; i++){
    deferreds.push($.get('data.json'))
  }

  $.when.apply(null, deferreds ).done(function(){
    console.log(arguments)
    for( var i=0; i<arguments.length; i++ ){
      var arg = arguments[i]
      var responseData = arg[0],
          statusText = arg[1],
          xhrObj =arg[2];
    }
  });

The arguments of $.when.apply().done(function() // or then will be in same order as the original deferreds array.

I believe jQuery 3 has streamlined $.when to be more in line with Promises A+ and to accept and return arrays but I haven't looked into it deeply

DEMO

Comments