使功能等待/“暂停”直到另一个完成

时间:2014-07-24 13:45:32

标签: javascript jquery callback

如何使函数仅在完成后调用的另一个函数之后继续。像这样:

function FunctionOne() {
  //Do something ...
  FunctionTwo()
  //Rest of the code after two is finished
}

function FunctionTwo() {
  //Some code
}

编辑:

确切的功能是这样的:

function FunctionOne() {
  //Do something ...
  var result;

  for (var i = 0 , i < 100 , ++i){
     result = FunctionTwo()
  }
  //Rest of the code after two is finished
  console.dir(result); //this here gives me undefined
}

function FunctionTwo() {
    $.get("url", function(data)
    {
       result = data;
       console.dir(result); //this gives me the data but the first function is still running and it finishes faster then the data is retured

       return result;
    }

2 个答案:

答案 0 :(得分:1)

您必须使用jQuery.ajax并设置async: false

一个简单的例子:

result = '';

function FunctionTwo() {
    jQuery.ajax({
                 url:    'url',
                 success: function(data) {
                              result = data;
                              console.dir(result); 
                          },
                 async:   false
    });

    alert(result);
}

答案 1 :(得分:-1)

这应该已经按照您的要求进行。除非您指定FunctioTwo以异步方式运行,否则它将阻止您。

编辑以响应您的修改: 如果你想要阻止Ajax调用,那么没有理由把它作为异步调用,如果你希望它保持异步,那么利用ajax调用的回调来执行你的数据处理函数,而不是把它放在主要街区。

function FunctionOne() {
  //Do something ...
  var result;

  for (var i = 0 , i < 100 , ++i){
     result = AJAXCall(i)
  }

}
function HandleAJAXResponse(response,id)
{
    console.dir(response)
}

function AJAXCall(id) {
    $.get("url",function(data,id){
        HandleAJAXResponse(data,id);
    });
}