Multiple Ajax requests (with one callback)

I am sending a few ajax requests and want to get a callback if all requests are successful. I found $.when($.ajax(), [...]).then(function(results){},[...]);, but it only works when you know in advance how much you are going to do. In my case, it depends on user input.

I tried the following, but I'm not sure where and how it $.whenfits:

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

        // ...some prep...

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

How to use the results of all these separate calls $.ajaxwith $.when? Or can I handle it differently?

+4
source share
3 answers

I think the general structure of what you are 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.
});
+5
source

$.when.apply($, arrayOfPromises): Promise.all:

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

Promise.all thenables , , . jQuery promises, , , thenables, .

Promise Promise shim/polyfill.

, :

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

    // ...some prep...

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

( $.map Array#map.)

:

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

jQuery:

$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).then( myFunc, myFailure );

myFunc, ajax , myFailure, .

, - :)

@TW80000:

var requests = [];
 ....
$.when.apply($, requests ).done( myFunc, myFailure );
0
source

Source: https://habr.com/ru/post/1650313/


All Articles