Rrr*_*nnn 165 javascript jquery
我有以下JavaScript代码:
$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable);
function2(someOtherVariable);
}
else {
doThis(someVariable);
}
});
Run Code Online (Sandbox Code Playgroud)
如何确保function2
仅在function1
完成后调用?
Mik*_*son 188
指定一个匿名回调,并使function1接受它:
$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable, function() {
function2(someOtherVariable);
});
}
else {
doThis(someVariable);
}
});
function function1(param, callback) {
...do stuff
callback();
}
Run Code Online (Sandbox Code Playgroud)
phi*_*kle 92
如果您使用的是jQuery 1.5,则可以使用新的Deferreds模式:
$('a.button').click(function(){
if(condition == 'true'){
$.when(function1()).then(function2());
}
else {
doThis(someVariable);
}
});
Run Code Online (Sandbox Code Playgroud)
编辑:更新的博客链接:
丽贝卡·墨菲对这个伟大的写在这里:http://rmurphey.com/blog/2010/12/25/deferreds-coming-to-jquery/
Tua*_*ong 39
试试这个 :
function method1(){
// some code
}
function method2(){
// some code
}
$.ajax({
url:method1(),
success:function(){
method2();
}
})
Run Code Online (Sandbox Code Playgroud)
Dom*_*see 36
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
});
}
Run Code Online (Sandbox Code Playgroud)
对于这个简单的示例来说,这似乎是一个重要的开销,但对于更复杂的代码,它远比使用回调更好.您可以使用多个then
语句轻松链接多个异步调用:
function1(someVariable).then(function() {
function2(someOtherVariable);
}).then(function() {
function3();
});
Run Code Online (Sandbox Code Playgroud)
您还可以轻松地包装jQuery deferrds(从$.ajax
调用返回):
Promise.resolve($.ajax(...params...)).then(function(result) {
//whatever you want to do after the request
});
Run Code Online (Sandbox Code Playgroud)
正如@charlietfl所说,实现接口jqXHR
返回的对象.所以实际上没有必要将它包装成a ,它可以直接使用:$.ajax()
Promise
Promise
$.ajax(...params...).then(function(result) {
//whatever you want to do after the request
});
Run Code Online (Sandbox Code Playgroud)
de *_*aad 19
或者,您可以在一个函数完成时触发自定义事件,然后将其绑定到文档:
function a() {
// first function code here
$(document).trigger('function_a_complete');
}
function b() {
// second function code here
}
$(document).bind('function_a_complete', b);
Run Code Online (Sandbox Code Playgroud)
使用此方法,函数'b'只能执行AFTER函数'a',因为触发器仅在函数a执行完毕时存在.
归档时间: |
|
查看次数: |
465514 次 |
最近记录: |