我有以下JavaScript代码:

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

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


当前回答

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

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


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

其他回答

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

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


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

你可以这样做

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

试试这个:

function method1(){
   // some code

}

function method2(){
   // some code
}

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

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

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执行完毕时存在。

这个答案使用了承诺,这是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
});