我需要按严格顺序调用一堆函数。同时,下一个函数等待前一个函数完成非常重要。
现在我正在使用链式回调:
callMe1(function(){
callMe2(function(){
callMe3(function(){
callMeFinal();
});
});
});
这个方法虽然可行,但看起来有点丑陋。
有没有其他不同的建议?
我需要按严格顺序调用一堆函数。同时,下一个函数等待前一个函数完成非常重要。
现在我正在使用链式回调:
callMe1(function(){
callMe2(function(){
callMe3(function(){
callMeFinal();
});
});
});
这个方法虽然可行,但看起来有点丑陋。
有没有其他不同的建议?
queue
来链接函数。$(document)
.queue(callMe1)
.queue(callMe2);
其中callMeX
应该是这种形式:
function callMeX(next) {
// do stuff
next();
}
$(document)
的地方,改为绑定到$({})
-- 这样队列内部的函数可以使用this
来引用同一个共享对象。 - gnarfvar calls = [];
function executeNext(next) {
if(calls.length == 0) return;
var fnc = calls.pop();
fnc();
if(next) {
executeNext(true);
}
}
/*To call method chain synchronously*/
calls.push(callMe3);
calls.push(callMe2);
calls.push(callMe1);
executeNext(true);
/*To call method chain asynchronously*/
calls.push(callMe3);
calls.push(function(){
callMe2();
executeNext(false);
});
calls.push(function(){
callMe1();
executeNext(false);
});
不确定这是否能帮到你,但有一篇关于在jQuery 1.5中使用延迟对象的好文章。它可能会使你的代码更简洁...
另外,我在有人可以解释一下jQuery队列吗?的答案中举了一些使用队列确保顺序调用的例子。
你可能想要向函数传递参数,但我认为目前还不能这样做。不过...
function callMe1(next) {
console.log(this.x);
console.log("arguments=");
console.log(arguments);
console.log("/funct 1");
this.x++;
next();
}
function callMe2(next) {
console.log(this.x);
console.log("arguments=");
console.log(arguments);
console.log("/funct 2");
this.x++;
next();
}
function callMe3(next) {
console.log(this.x);
console.log("arguments=");
console.log(arguments);
console.log("/funct 3");
this.x++;
next();
}
var someObject = ({x:1});
$(someObject).queue(callMe1).queue(callMe2).queue(callMe3);
使用匿名函数将您的函数及其参数包装起来,然后与.queue
一起使用也可以。
var logger = function(str, callback){
console.log(str);
//anything can go in here, but here's a timer to demonstrate async
window.setTimeout(callback,1000)
}
$(document)
.queue(function(next){logger("Hi",next);})
.queue(function(next){logger("there,",next);})
.queue(function(next){logger("home",next);})
.queue(function(next){logger("planet!",next);});
JSFiddle上的示例:http://jsfiddle.net/rS4y4/