我有以下 JavaScript 代码:
$('a.button').click(function(){
    if (condition == 'true'){
        function1(someVariable);
        function2(someOtherVariable);
    }
    else {
        doThis(someVariable);
    }
});
如何确保function2仅在function1完成后才调用?
我有以下 JavaScript 代码:
$('a.button').click(function(){
    if (condition == 'true'){
        function1(someVariable);
        function2(someOtherVariable);
    }
    else {
        doThis(someVariable);
    }
});
如何确保function2仅在function1完成后才调用?
指定一个匿名回调,并让 function1 接受它:
$('a.button').click(function(){
    if (condition == 'true'){
        function1(someVariable, function() {
          function2(someOtherVariable);
        });
    }
    else {
        doThis(someVariable);
    }
});
function function1(param, callback) {
  ...do stuff
  callback();
} 
如果您使用的是 jQuery 1.5,则可以使用新的 Deferreds 模式:
$('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/
试试这个 :
function method1(){
   // some code
}
function method2(){
   // some code
}
$.ajax({
   url:method1(),
   success:function(){
   method2();
}
})
promises的 JavaScript 特性ECMAScript 6。如果您的目标平台不支持promises,请使用PromiseJs对其进行polyfill。Promise 是一种在 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 deferrds(从$.ajax调用中返回):
Promise.resolve($.ajax(...params...)).then(function(result) {
    //whatever you want to do after the request
});
正如@charlietfl 所指出的,jqXHR返回的对象$.ajax()实现了Promise接口。所以其实没必要用a包裹Promise,直接使用即可:
$.ajax(...params...).then(function(result) {
    //whatever you want to do after the request
});
或者您可以在一个函数完成时触发自定义事件,然后将其绑定到文档:
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 执行完毕后才存在。