0

I have multiple ajax calls that I am making at one time. Once they are all done, I need to redirect the user to another page.

With the help of this answer, I created this:

function verifyAll() {
    var ajaxCalls = [];
    $.each($('.thing'), function(index, thing) {
        ajaxCalls.push(verifyOne($(thing).data('id'));
    });

    $.when(ajaxCalls).done(function() {
        console.log('Done verifying all');
    });
}

function verifyOne(id) {
    return $.ajax({
        type: 'GET',
        url: 'verify.html'
    }).done(function(data) {
        console.log('Done verifying one');
        //do something
    });
}

However, the $.when().done() function is called BEFORE the .done() is called on the individual ajax. Is there something I am doing wrong or is there another way to achieve my end goal?

Community
  • 1
  • 1
Harry
  • 772
  • 10
  • 32
  • use `$.when` to pass it an array of async functions – Daniel Lizik Jul 27 '16 at 15:38
  • Notice the difference between your code which passes an array of deferreds to `when` and the linked code which passes a number of arguments - that is relevant – Jamiec Jul 27 '16 at 15:40

1 Answers1

2

$.when() doesn't support arrays directly

Try

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

    console.log('Done verifying all');
    console.log(arguments);
});
charlietfl
  • 170,828
  • 13
  • 121
  • 150