0

I can pass in multiple ajax calls into a when like this:

var dnldAy = [];
for (i=0, iMax=urlsToLoad.length; i < iMax; i++) {
    dnldAy.push( $.ajax({
        url: urlsToLoad[i],
        dataType: "json"
    }) );
}

$.when.apply($, dnldAy).done( function( doneCb ) {
    console.log( doneCb );
}

When when runs it is only getting the first doneCb from the array of ajax requests. I understand I could add more parameters to the done function to get the other callbacks, but this is not extensible. (I am going to have an unknown number of ajax calls in my when, so I cannot know how many parameters I will need in the done function ahead of time).

What is the right way to handle this design problem?

jedierikb
  • 12,752
  • 22
  • 95
  • 166

1 Answers1

3

The first example in the documentation for jQuery.when() shows how to access the arguments for the individual promises.

However it doesn't address how to approach an unknown number of promises, for which little extra knowledge is necessary - namely that a function's arguments are made available in the array-like object arguments, which can be looped through as follows.

$.when.apply($, dnldAy).done( function() {
    for(i=0; i<arguments.length; i++) {
        var doneCb = arguments[i];
        console.log( doneCb );
    }
}

Each doneCb will itself be an array containing the value(s) with which the corresponding promise was resolved.

Beetroot-Beetroot
  • 18,022
  • 3
  • 37
  • 44