Code execution after multiple AJAX calls

Before this is marked as a duplicate, I looked at several articles on stackoverflow and they don't seem to answer my question.

I am creating a plugin with api that uses http requests for its calls. I have a main loop that runs multiple times with several different AJAX requests inside it. I need to execute the code after all requests have completed.

The main problem I am facing is that the array containing all the promise objects is either empty or mostly empty by the time the function is reached $.when

, causing the code to run before everything is complete.

Here's a basic, simplified outline of the code:

var xhrs = [];
var xhr = null;

$.each(array, function(index, el) {
    // Step 1
    xhr = ajaxCall.success(function() {
        xhr = ajaxCall2();
        xhrs.push(xhr);
    });
    xhrs.push(xhr);

    // Step 2
    xhr = $.getJSON(params, function() {
        //...stuff...

        // Step 3
        var xhrs2 = [];
        $.each(function() {
            xhr = ajaxCall3();
            xhrs.push(xhr);
            xhrs2.push(xhr);
        });

        // Step 4
        xhr = ajaxCall4().success(function() {
            xhr = ajaxCall5().success(function() {
                //....
            });
            xhrs.push(xhr);
        });
        xhrs.push(xhr);


        // Step 5
        $.when(xhrs2).then(function() {
            $.each(function() {
                xhr = ajaxCall5();
                xhrs.push(xhr);
            });
        });

    });
    xhrs.push(xhr);
});


$.when.apply($, xhrs).then(function() {
    // Run when all ajax calls completed
});

      

I've tried moving it to different locations and no luck. Any ideas?

+3


source to share


2 answers


The function $.when

takes each of the XHRs as arguments, then you can answer in then

when

. Each of the responses is passed as a separate argument.



$.when(xhr1, xhr2, xhr3).then(function(resp1, resp2, resp3) {
    // All 3 XHRs finished
});

      

+1


source


Have you tried making each request synchronous? A simple synchronous request in jquery looks like this:



jQuery.ajax({
     url:    'http://example.com' ,
     success: function(result) {
                      //Do stuff with result
              },
     async:   false
});

      

-3


source







All Articles