使函数等待/暂停;直到另一个结束

Make a function wait/"pause" till another one finishes

本文关键字:另一个 结束 暂停 函数 等待      更新时间:2023-09-26

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

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;
    }

必须使用jQuery。设置async: false

一个简单的例子:

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

这应该已经按照您的要求完成了。除非你指定functionotwo异步运行,否则它会为你阻塞。

编辑回应你的编辑:如果你想让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);
    });
}