javascript函数在变量获得值后执行

时间:2016-06-07 14:54:04

标签: javascript jquery

可以在JavaScript中获得某个变量值(或更改)后执行函数吗? 在我的示例中,variable首先被提升,被声明为全局,然后将在getData()函数中为其分配一些值。

我尝试过使用.delay()方法,但我不知道ajax需要多长时间。

简要描述:

1)声明variable

2)调用getData()函数,然后将数据分配给变量

3)调用funcA()函数

4)调用funcB()函数并将函数doSomething()作为funcA()

中的回调函数传递

5)在funcB()

中调用回调函数

6)在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>

1 个答案:

答案 0 :(得分:0)

将您的getdata更改为:

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