Dealing with Async calls in Javascript
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 t开发者_运维问答hree 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.
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){
}
});
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.
精彩评论