I'm trying to figure out how to accomplish this workflow, but can't seem to nail it. I've got n number of <select>
elements on a page. When the page loads, for each <select>
element, I need to make a $.get(...);
call. Once all of those calls are done, then, and only then do I need to run an additional function. Here is some example code to better explain:
function doWork(selectEl) {
var getData = ...; // build request data based on selectEl
$.get('/foo/bar', getData, function (data) {
// Do something to selectEl with the result
});
}
function doMoreWork() {
// Do something with all the selects now that they are ready
}
$(function () {
// For each of the select elements on the page
$('select').each(function(index, selectEl) {
// Go do some AJAX-fetching of additional data
doWork(selectEl);
});
// Once *all* the $.get(...) calls are done, do more things
doMoreWork();
});
Using the code above, doMoreWork()
is usually called before all of the async $.get(...);
calls have had a chance to return; which is not what I want. I need to have all of the $.get(...);
calls complete before doMoreWork()
can be called. Basically I need a callback of sorts to execute once ALL of the $.get(...);
calls in the above example have finished.
How would I go about accomplishing this?
Every time you call doWork
, increment a counter.
Every time a response comes back, decrement the counter.
Have the callback invoke doMoreWork
when the counter reaches 0
.
var counter = 0;
function doWork(selectEl) {
counter++;
var getData = ...; // build request data based on selectEl
$.get('/foo/bar', getData, function (data) {
counter--;
if( !counter ) { doMoreWork(); }
});
}
function doMoreWork() {
// Do something with all the selects now that they are ready
}
$(function () {
// For each of the select elements on the page
$('select').each(function(index, selectEl) {
// Go do some AJAX-fetching of additional data
doWork(selectEl);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With