Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 want 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.. }

};
like image 462
Russell Avatar asked Sep 02 '10 07:09

Russell


2 Answers

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

like image 160
Jerome WAGNER Avatar answered Sep 23 '22 11:09

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);
like image 32
fantactuka Avatar answered Sep 20 '22 11:09

fantactuka