ryudice
ryudice

Reputation: 37406

jquery pattern for multiple continuous ajax request

I have a for each loop with an array, for each element in the array I need to retrieve data from the server so I will make an ajax request per element and store the result in another array, I need to know when the last element in the array has been processed so I can display the data, is there a pattern or how could I do this without over complicating things which I think is what I'm doing

Upvotes: 4

Views: 883

Answers (3)

Adam Bergmark
Adam Bergmark

Reputation: 7546

A continuation passing library that has a "parallel" mode will abstract this nicely. I'm using JooseX-CPS, also see its tutorial.

Upvotes: 1

jamie-wilson
jamie-wilson

Reputation: 1925

For each on success you hit, count up the successful results and then trigger an event.

For example:

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

and then listen for your event

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

This lets you test the completion somewhere outside of the loop.

Upvotes: 0

alex
alex

Reputation: 490443

var array = ['a', 'b', 'c'],
    arrayLength = array.length,
    completed = 0;

Then, in the callbacks of your XHR,

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

completed++;

Alternatively, you state that you are adding the things to a new array. Assuming that when finished the arrays will be of equal length, you can change the check in the callback to (startArray.length == newArray.length).

Also, keep in mind if you are making XHR (assuming asynchronous) in a loop, they will all be trying to request at roughly the same time (I think), which may be an issue with performance. Consider writing a function which is called again on each individual request's callback, so the XHRs are made one at a time. Increment a counter so you can subscript the next array element in each call.

Upvotes: 2

Related Questions