Javascript is waiting for a function response

I have the following code:

myFunc(); bar(); 

myFunc () makes an ajax request

I do not want to execute bar () until the request to myFunc () is complete.

I also don't want to move the call to bar () inside myFunc.

perhaps?

EDIT

Here is the code I ended up in:

 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.. } }; 
+7
javascript ajax
source share
4 answers

To accomplish what you are looking for, you must find a way for bar () to communicate with myFunc ().

When you say you don't want to move the call to bar () inside myFunc (), this can be interpreted in several ways.

For example, you can make bar () the parameter 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 helps you

Jerome Wagner

+6
source share

IF you can add some kind of flag that indicates that myFunc () has completed its request, you can do it, but it is not a good idea - callbacks are best.

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); 
+1
source share

No, it’s not possible if you are not using a synchronous request, which is no longer AJAX, and something that I would not recommend you to do, since it will freeze the user interface until the request completes and users do not want to freeze them browser.

0
source share

No, It is Immpossible.

You can achieve this with a side effect that you block your browser by making an SJAX request instead of an AJAX request, but this is a terrible idea.

Learn to love event-driven programming while working in an event-driven programming environment.

0
source share

All Articles