I would like to do a series of get requests, and then preform some action after all of the get requests have finished. Below is a starting point on the code I have, but since the get request is asynchronous, the "do some action after all getJSON requests finish" executes right away.
What is the proper/best way of going about this?
...
$.each(array, function(i, element) {
// setup url and params
$.getJSON(url, params, function(data) {
// do work on data
}
}
// do some action after all getJSON requests finish
...
I considered having a counter for the number of elements in the array, decrementing it, and performing the action when it reaches zero, but I am worried that the operation is not atomic and may encounter errors. Below is an example of what I was thinking of, but I am uncertain if it would always work correctly.
...
$.each(array, function(i, element) {
var items_remaining = array.length;
// setup url and params
$.getJSON(url, params, function(data) {
// do work on data
items_remaining = items_remaining - 1;
if ( items_remaining === 0 ) {
// do some action after all getJSON requests finish
}
}
}
....