0

I've got into a small trouble here. In my document.ready function I've defined an object and that object is being populated by three different ajax calls(inside document.ready). Now I want to do a

 console.log(myObject);

only when the 3 async calls have been executed completely. Please suggest a way to do this.

2 Answers 2

3

Using I would suggest you to create a function like this:

function onAllInformationIsReady() {
        console.log(myObject);
    }

function isAllInformationReady() {
    // verify here if you have all the information
}

and you do something like this on your ajax calls (I'm not assuming you are using jQuery here, replace with your ajax call method)

$.ajax({
    type: "POST",
    url: "some.php",
    data: "...n",
    success: function(msg){

     if(isAllInformationReady())
        onAllInformationIsReady();

    }
});

By the way, if you are using jQuery you can make synchronous ajax calls like this:

$.ajax({
        type: "POST",
        url: "some.php",
        data: "...n",
        async: false,
        success: function(msg){

        }
    });
Sign up to request clarification or add additional context in comments.

2 Comments

yes, I'm using jQuery, but the issue is that I'm making 3 simultaneous calls. In who's success part should I call my method?
don't - use the $.when method from my answer which is now the "right" way to handle collation of multiple asynchronous tasks in jQuery.
3

Try jQuery 1.5's new "deferred" objects:

var j1 = $.ajax(...);
var j2 = $.ajax(...);
var j3 = $.ajax(...);

j1.success(function(data) {
    // do something with data
});

j2.success(function(data) {
    // do something with data
});

j3.success(function(data) {
    // do something with data
});

$.when(j1, j2, j3).done(function() {
    console.log(myObject);
});

The three .success() functions will be called asynchronously and will populate myObject, and then the done function will only be invoked by $.when() once all three AJAX requests have been completed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.