我有以下JavaScript代码:

$('a.button').click(function(){
    if (condition == 'true'){
        function1(someVariable);
        function2(someOtherVariable);
    }
    else {
        doThis(someVariable);
    }
});

如何确保函数2只在函数1完成后才被调用?


当前回答

试试这个:

function method1(){
   // some code

}

function method2(){
   // some code
}

$.ajax({
   url:method1(),
   success:function(){
   method2();
}
})

其他回答

如果方法1必须在方法2、3、4之后执行。下面的代码片段可以使用JavaScript中的Deferred对象来解决这个问题。

function method1(){ var dfd = new $.Deferred(); setTimeout(function(){ console.log("Inside Method - 1"); method2(dfd); }, 5000); return dfd.promise(); } function method2(dfd){ setTimeout(function(){ console.log("Inside Method - 2"); method3(dfd); }, 3000); } function method3(dfd){ setTimeout(function(){ console.log("Inside Method - 3"); dfd.resolve(); }, 3000); } function method4(){ console.log("Inside Method - 4"); } var call = method1(); $.when(call).then(function(cb){ method4(); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

指定一个匿名回调函数,并使函数1接受它:

$('a.button').click(function(){
    if (condition == 'true'){
        function1(someVariable, function() {
          function2(someOtherVariable);
        });
    }
    else {
        doThis(someVariable);
    }
});


function function1(param, callback) {
  ...do stuff
  callback();
} 

这取决于函数1在做什么。

如果function1正在执行一些简单的同步javascript,比如更新div值之类的,那么function2将在function1完成后触发。

如果function1正在进行异步调用,例如AJAX调用,您将需要创建一个“回调”方法(大多数AJAX API都有一个回调函数参数)。然后在回调中调用function2。例如:

function1()
{
  new AjaxCall(ajaxOptions, MyCallback);
}

function MyCallback(result)
{
  function2(result);
}

你可以这样做

$.when(funtion1()).then(function(){
    funtion2();
})

这个答案使用了承诺,这是ECMAScript 6标准的一个JavaScript特性。如果您的目标平台不支持promise,请使用PromiseJs填充它。

承诺是JavaScript中处理异步操作的一种新的(更好的)方式:

$('a.button').click(function(){
    if (condition == 'true'){
        function1(someVariable).then(function() {
            //this function is executed after function1
            function2(someOtherVariable);
        });
    }
    else {
        doThis(someVariable);
    }
});


function function1(param, callback) {
    return new Promise(function (fulfill, reject){
        //do stuff
        fulfill(result); //if the action succeeded
        reject(error); //if the action did not succeed
    });
} 

对于这个简单的示例,这似乎是一个很大的开销,但对于更复杂的代码,它比使用回调要好得多。你可以使用多个then语句轻松链接多个异步调用:

function1(someVariable).then(function() {
    function2(someOtherVariable);
}).then(function() {
    function3();
});

您还可以轻松地包装jQuery延迟(从$。ajax调用):

Promise.resolve($.ajax(...params...)).then(function(result) {
    //whatever you want to do after the request
});

正如@charlietfl指出的,$.ajax()返回的jqXHR对象实现了Promise接口。所以实际上没有必要把它包装在Promise中,它可以直接使用:

$.ajax(...params...).then(function(result) {
    //whatever you want to do after the request
});