0

Can function be executed after some variable got value (or changed) in JavaScript? In my example, the variable is hoisted at first which is declared to be a global, then will assign some value to it in getData() function.

I have tried using .delay() method, but i don't know how much time the ajax needs.

briefly describe:

1) Declaring variable

2) calling getData() function, then assign the data to variable

3) calling funcA() function

4) calling funcB() function and pass function doSomething() as a callback in funcA()

5) calling the callback function in funcB()

6) log the data in doSomething()

<script>
    var variable;
    variable = getData();
    funcA();

    function funcA() {
      funcB(doSomething);

      function doSomething(data) {
        console.log(data);
      }
    }

    function funcB(callback) {
      if (variable !== undefined) {//it is obviously undefined.
        callback(variable);
      }
    }
    </script>

    //another js file
    <script>
    function getData() {
      //get data by using ajax
      //i don't know how much time it needs.
      return data;
    }
    </script>
king yau
  • 500
  • 1
  • 9
  • 28
  • You already seem to know about callbacks - the most correct answer to this problem will be to pass a callback to your ajax mechanism for it to call when it's done. – James Thorpe Jun 07 '16 at 14:56
  • why not just calling everything you need to do after the assignment. – Roozbeh Jun 07 '16 at 15:02
  • @Roozbeh hz i have update my example – king yau Jun 07 '16 at 15:05
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – James Thorpe Jun 07 '16 at 15:09
  • Your edit makes it a dupe of the linked question - in that it shows how to use callbacks to return information back. Essentially you'll need to pass a callback function as a parameter to `getData()`. – James Thorpe Jun 07 '16 at 15:10

1 Answers1

0

change your getdata to this:

function getData() {
    $.ajax({
    url: "some url",
    success: function(result){
        variable = result;
        //do everything that should be done here or call your callback
    });
}
Roozbeh
  • 462
  • 3
  • 14