Javascript 如何避免回调链?
我需要按严格的顺序调用一组函数。下一个函数等待上一个函数完成也是非常重要的 现在我正在使用链式回调:Javascript 如何避免回调链?,javascript,jquery,callback,Javascript,Jquery,Callback,我需要按严格的顺序调用一组函数。下一个函数等待上一个函数完成也是非常重要的 现在我正在使用链式回调: callMe1(function(){ callMe2(function(){ callMe3(function(){ callMeFinal(); }); }); }); 这是可行的,但似乎有点难看 有没有其他方法的建议?您可以实施“堆栈”系统: 如果使用jQuery,则可以使用来链接函数 $(document)
callMe1(function(){
callMe2(function(){
callMe3(function(){
callMeFinal();
});
});
});
这是可行的,但似乎有点难看
有没有其他方法的建议?您可以实施“堆栈”系统:
如果使用jQuery,则可以使用来链接函数
$(document)
.queue(callMe1)
.queue(callMe2);
其中,callMeX
的格式应为:
function callMeX(next) {
// do stuff
next();
}
我不确定这是否对你有帮助,但是有一篇很好的文章。它可能会清理一下你的链条
另外,我在上的回答中有一些使用队列确保顺序调用的示例。您可能希望将参数传递给函数,我相信在撰写本文时您不可能这样做。然而
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
一起使用的匿名函数完整地包装函数和参数
在Jquery.Queue()中传递参数
关于JSFIDLE的示例:我会尝试给您一个关于如何重新排列代码以避免这些情况的好答案,但是这个非常简单的代码示例并没有真正深入到为什么这些函数当前是这样链接的……去年我问过的一个类似的问题队列非常棒。。。一个建议是,不要绑定到
$(document)
绑定到$({})
——这样队列中的函数就可以使用this
引用同一个共享对象。如果没有jquery的队列,这可能是最好的解决方案it@Meister-在调用方法链中异步,如何调用回调?因为只有推动动作
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);
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);});