Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140788

How can I make many AJAX requests, then call a function when they have all completed?

$
0
0

I have the following function that returns a jQuery deferred object:

function performAjaxRequest(arg1, arg2, arg3) {
    return $.ajax({
        url: someurl,
        type: "POST",
        data: { arg1: arg1, arg2: arg2, arg3: arg3 }
        success: function(data) {
            //do something
        },
        error: function(data) {
            //do something else
        }
   });
}

Next, I have the following function which does some processing, then calls the function above inside a loop. Finally, it pushes the deferred objects returned by performAjaxRequest() into an array and returns the array:

function putDeferredsInArray() {
    //do some processing
    var deferreds = [];
    var arg1, arg2, arg3 = []; //these arrays are being populated, but that is not important
    var someCount = $('#someFieldThatHasCount').val();
    for (var i = 0; i < someCount; i++) {
        //put the deferred objects in array
        deferreds.push(performAjaxRequest(arg1[i], arg2[i], arg3[i]));
    }
    return deferreds;
}

Finally, I have one last function that completes processing by calling .done for the deferred objects returned from the above function:

function completeProcessing() {
    putDeferredsInArray().done(someCallback(arg)); //getting the error here
}

Have I left something out? For some reason, someCallback(arg) is called even though I'm getting an error that says "Object doesn't support property or method 'done'". My understanding of jQuery deferred objects may be incomplete, so please correct me if my implementation is wrong. I just need the callback function to run after every AJAX request is complete.


Viewing all articles
Browse latest Browse all 140788

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>