我有以下JavaScript代码:

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

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


当前回答

如果你正在使用jQuery 1.5,你可以使用新的延迟模式:

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

编辑:更新博客链接:

丽贝卡·墨菲在这里写了一篇很棒的文章:http://rmurphey.com/blog/2010/12/25/deferreds-coming-to-jquery/

其他回答

如果方法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>

如果你正在使用jQuery 1.5,你可以使用新的延迟模式:

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

编辑:更新博客链接:

丽贝卡·墨菲在这里写了一篇很棒的文章:http://rmurphey.com/blog/2010/12/25/deferreds-coming-to-jquery/

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

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


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

或者你可以在一个函数完成时触发一个自定义事件,然后将其绑定到文档:

function a() {
    // first function code here
    $(document).trigger('function_a_complete');
}

function b() {
    // second function code here
}

$(document).bind('function_a_complete', b);

使用此方法,函数'b'只能在函数'a'之后执行,因为触发器仅在函数a执行完毕时存在。

你可以这样做

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