3 回答
TA貢獻1863條經驗 獲得超2個贊
指定匿名回調,并使function1接受它:
$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable, function() {
function2(someOtherVariable);
});
}
else {
doThis(someVariable);
}
});
function function1(param, callback) {
...do stuff
callback();
}
TA貢獻1875條經驗 獲得超5個贊
這個答案使用promises了ECMAScript 6標準的JavaScript功能。如果您的目標平臺不支持promises,請使用PromiseJs對其進行填充。
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返回的對象。所以實際上沒有必要將它包裝成a ,它可以直接使用:$.ajax()PromisePromise
$.ajax(...params...).then(function(result) {
//whatever you want to do after the request
});
添加回答
舉報
