26

Using the Deferred pattern from jQuery http://api.jquery.com/jQuery.when/, I am trying to make multiple jsonp ajax calls and wait for the results before moving to the next step. I can accomplish this using a fixed amount of calls because I can set the number of resolved argument parameters in the ".done()" deferred object. But in my application it doesn't work because the number of calls is dynamic and always unknown.

This first simplified example works because I can set the number of args in the .done() resolved function. I know I need two because there are two calls in the .when():

$.when( $.ajax( url1 ), $.ajax( url2 ) ).done(function( a1, a2 ) {  
    var data = a1[ 0 ] + a2[ 0 ]; 
});

This is what I need but can't get it to work:

var urls = GetUrlList(); // returns array of urls to json service
var requests = []; // hold ajax request
for (i = 0; i < urls.length; i++) {
    requests.push($.ajax(url[i]));
}

$.when.apply($, requests).done(function ("what goes here?") {
    // Need to get the data returned from all ajax calls here
});

Thanks for any help on this!

Xay Xayay
  • 263
  • 3
  • 5

1 Answers1

37

You can use arguments, which is a special king of object holding all arguments passed to a function

$.when.apply($, requests).done(function () {
    console.log(arguments); //it is an array like object which can be looped
    var total = 0;
    $.each(arguments, function (i, data) {
        console.log(data); //data is the value returned by each of the ajax requests

        total += data[0]; //if the result of the ajax request is a int value then
    });

    console.log(total)
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • 1
    This works well when you have at least two requests to send. Otherwise you get an inconsistent behavior when it's one query or several :( – Happynoff Sep 29 '16 at 11:26
  • 1
    the link to arguments is out of date and points to a deprecated feature. The [updated link is this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments) – Liam Jan 05 '17 at 11:18
  • 1
    this is not perfect. I called this with 1 argument, but 2 arguments arrived, of which the second is the string literal `success` – phil294 Jul 27 '17 at 11:57