BlueChips23
BlueChips23

Reputation: 1951

Using callbacks in window.onload

I think there is an easy solution for this, but for some reason I am not getting the expected results. My functions look like this:

var functionA = function(callback) {
    loadData(fromURL1); // takes some time
    loadData(fromURL2); // takes some time
    callback();         // Should be called AFTER the loadData() functions are finished
}

var myCallBackFunction = function() {
  // this function is called AFTER functionA() is finished
  alert("All my loaded data from URL1 and URL2");
}

window.onload = function() {
   functionA(myCallBackFunction);
}

Unfortunately, the callback() function above doesn't wait for loadData() to finish, and then just calls the alert with empty data.

I read a lot of online examples, but I think I am still missing something obvious.

Upvotes: 0

Views: 1175

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

If the loadData()s are async operations, you can do two things:

Using $.ajaxComplete():

var functionA = function(callback) {
    loadData(fromURL1); // takes some time
    loadData(fromURL2); // takes some time
    $.ajaxComplete(function () {
        callback();         // Should be called AFTER the loadData() functions are finished
    });
}

Or chaining the functions:

var functionA = function(callback) {
    loadData(fromURL1, function () {
       loadData(fromURL2, function () {
           callback();         // Should be called AFTER the loadData() functions are finished
       }); // takes some time
    }); // takes some time
}

Upvotes: 1

Related Questions