Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I defer this javascript call?

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?

like image 922
ckittel Avatar asked Aug 24 '11 19:08

ckittel


1 Answers

  1. Every time you call doWork, increment a counter.

  2. Every time a response comes back, decrement the counter.

  3. 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);
    });
});
like image 120
user113716 Avatar answered Sep 25 '22 17:09

user113716