0

I've read a lot of threads on here and haven't found an answer that satisfies my problem.

Basically I'm building n AJAX calls and want to do something only once they've all returned.

But whatever I try, done() the callback fires too early. Here's my code:

    // turn the URL array into an AJAX request array
    for (var i=0; i<mediaRequests.length; i++) {
        mediaRequests[i] = $.ajax(mediaRequests[i], {dataType: 'jsonp'});
    }

    $.when($, mediaRequests).done(function() {
        var responses = arguments[1];

        // for each response...
        for (var i=0; i<responses.length; i++) {
            var data = responses[i].responseJSON;
            console.log(data);
        }
    });

But the console prints out undefined.

Why isn't $.when($, mediaRequests).done() giving me the responses?

Sean H
  • 1,045
  • 1
  • 14
  • 32
  • 1
    There's been a similar question already (with a valid answer): https://stackoverflow.com/questions/6538470/jquery-deferred-waiting-for-multiple-ajax-requests-to-finish – LongHike May 31 '17 at 10:38

1 Answers1

0

Hello you could use defferreds array with apply like this :

$.when.apply($, mediaRequests).done(function(){

Instead of:

$.when($, mediaRequests).done(function() {

When you know how many ajaxes you are calling you can do this (lets say there are 3 of them):

$.when.apply($, mediaRequests).done(function(result1,result2,result3){
// now result1 got result from first ajax, result2 from second ajax and so on
Redrif
  • 650
  • 4
  • 22