Javascript wait for function response
I have the following code:
myFunc();
bar();
myFunc() is making an ajax request
I don't want to execute bar() until myFunc()'s request has completed.
I also do not wa开发者_JAVA百科nt to move the call to bar() inside of myFunc.
possible?
EDIT
Here is the code I ended up with:
var FOO = {
init: function(blah)
{
// Callbacks to pass to the AJAX challenge data load
var callbacks = {
myFunc1: function(){ myFunc1(blah); },
myFunc2: function(){ myFunc2(blah); },
};
this.bar(callbacks); // Load the challenge data and setup the game
},
bar: function(callbacks) { ..loop through and execute them.. }
};
In order to do what you are looking for, you must find a way for bar() to communicate with myFunc().
When you say that you do not want to move the call to bar() inside myFunc() this can be interpreted in several ways.
For example, you could make bar() a parameter of myFunc()
function bar() {
// do what bar() does
}
function myFunc(callback) {
// use callback in the onreadystatechange property of the xmlhtprequest object
}
myFunc(bar)
I hope this will help you
Jerome Wagner
IF you can add a kind of a flag that will indicate that myFunc() has finished with its request you can do it, but this is not a good idea - best practice is to use callbacks.
Try this code:
var successRequest = false;
myFunc(); // when get the response set successRequest to true
var interval = setInterval(function() {
if (successRequest) {
clearInterval(interval);
bar();
}
}, 100);
No, not possible unless you use a synchronous request which is no longer AJAX and something I wouldn't recommend you doing as it will freeze the UI until the request completes and users hate having their browser freezing.
No, it is not possible.
You could achieve it with the side effect that you lock up the browser by making a SJAX request instead of an AJAX request, but that is a terrible idea.
Learn to love event driven programming when you work in an event driven programming environment.
精彩评论