Jquery template for multiple continuous ajax request

I have for each loop with an array, for each element in the array I need to get data from the server, so I will make an ajax request for each element and save the result in another array, I need to know when the last element in the array is processed, so I can display data, is there a template or how can I do this without over-complicating things that I think is what I do

+4
source share
3 answers
var array = ['a', 'b', 'c'], arrayLength = array.length, completed = 0; 

Then in your XHR callbacks

 if (completed == arrayLength) { // All of them have finished. } completed++; 

Alternatively, you indicate that you are adding things to the new array. Assuming the arrays will be the same length upon completion, you can change the callback check to (startArray.length == newArray.length) .

Also, keep in mind that if you do XHR (assuming asynchronous) in a loop, they will all try to query at about the same time (I think), which could be a performance issue. Consider writing a function that is called again for each individual request callback, so XHRs are created one at a time. Increase the counter so you can index the next element of the array in each call.

+2
source

Passing continuation library, which has a "parallel" mode, abstract is abstract. I use JooseX-CPS , also see its tutorial .

+1
source

For each success, you hit, count the successful results and then fire the event.

For instance:

 var successfulReturns= 0; $.ajax({ url:"", success: function() { successfulReturns++; $(document).trigger("myapp.loadedComplete"); } }); 

and then listen to your event

 $(document).bind("myapp.loadedComplete", function() { } ); 

This allows you to check for completion somewhere outside the loop.

0
source

All Articles