Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Ajax Requests (with one callback)

I'm sending multiple ajax requests and want to get a callback if all the requests are successful. I've found $.when($.ajax(), [...]).then(function(results){},[...]); but that only works when you know in advance how many you're going to do. In my case, it varies depending on user input.

I tried the following but I'm not sure where or how $.when fits in:

$.when(
    $('#piecesTable tr').not(':first').each(function(){

        // ...some prep...

        $.ajax({
            // ...args here...
        });
    })
).then(function() {
    // All requests are done
});

How do I use the results of all those separate $.ajax calls with $.when? Or do I handle this some other way?

like image 869
H.C Avatar asked Jan 06 '23 14:01

H.C


2 Answers

I think the general structure of what you're looking for is something like this:

var requests = [];

// Populate requests array with ajax requests.
requests.push($.ajax({
    // ...
}));

// Add as many requests as you want to the array.

$.when.apply($, requests).done(function() {
    var args = $.prototype.slice.call(arguments);

    // args should contain the results of your ajax requests.

    // Do whatever with the results.
});
like image 185
TW80000 Avatar answered Jan 08 '23 05:01

TW80000


There's a modern alternative to the $.when.apply($, arrayOfPromises) beast: Promise.all:

Promise.all(arrayOfPromises).then(function(arrayOfResults) {
    // Use arrayOfResults
});

Promise.all expects an array of thenables and returns a promise that resolves with an array of the results when all of the thenables have resolved. It's fine with jQuery's promises, because all it requires is that they be thenables, which they are.

You can use this on any browser with Promise support, or if you include a Promise shim/polyfill.

So in your case, you'd build the array:

var arrayOfPromises = [];
$('#piecesTable tr').not(':first').each(function(){

    // ...some prep...

    arrayOfPromises.push($.ajax({       // ** Push this promise into the array
        // ...args here...
    }));
});

(Or you can build it with $.map or Array#map.)

And then use the array:

Promise.all(arrayOfPromises).then(function(arrayOfResults) {
    // Use arrayOfResults
});
like image 30
T.J. Crowder Avatar answered Jan 08 '23 04:01

T.J. Crowder