我有一个场景,我想将 2 个或更多函数(作为参数)发送到处理函数中,并让该处理函数执行每个传递的函数作为前面函数的回调函数。
这是我试图编写的函数的一般概念:
function functionChain() {
// MAKE SURE WE HAVE AT LEAST 1 PARAMETER
if ( arguments.length < 1 ) { return; }
// for each parameter, call it (as a function)
for ( var i=0; i<arguments.length; i++) {
if ( typeof arguments[i] === 'function' ) {
call arguments[i];
}
}
}
// example
functionChain( function1, function2, function3 );
...所以在上面的代码中,每个函数都会被连续调用。
我遇到困难的是如何在前一个函数完成时将每个调用视为回调。
我处理这个问题的方法是有一个变量(为了简单起见,我们只说一个名为 functionChainComplete 的全局变量),然后等待启动下一个函数——当然,我调用的每个函数都会将 functionChainComplete 设置为 true。所以,像这样:
// set global var for tracking
var functionChainComplete;
function functionChain() {
// MAKE SURE WE HAVE AT LEAST 1 PARAMETER
if ( arguments.length < 1 ) { return; }
// SET GLOBAL VAR TO FALSE
functionChainComplete = true;
// for each parameter, call it (as a function)
for ( var i=0; i<arguments.length; i++) {
if ( typeof arguments[i] === 'function' ) {
if ( functionChainComplete == true ) {
// call the next function and wait for true again
functionChainComplete = false;
call arguments[i];
} else {
// try again in 50 ms (maybe setTimeout)?
}
}
}
}
function1() {
// do something, and when done, reset functionChainComplete
functionChainComplete = true;
}
function2() {
// do something, and when done, reset functionChainComplete
functionChainComplete = true;
}
function3() {
// do something, and when done, reset functionChainComplete
functionChainComplete = true;
}
// example
functionChain( function1, function2, function3 );
正如您所看到的,上面的代码没有解决回调部分,我不知道从哪里获取它 - 我怀疑某种递归函数?我被困住了。