[英]chaining functions with a function argument
What I'm trying to do is 'connect' an array of functions together with a function. 我想做的是将一个函数数组与一个函数“连接”在一起。 So in an array of functions:
因此,在一系列函数中:
var functionArray = [functionA, functionB, functionC];
functionA(next)
should be able to invoke a call to its function argument next
to call functionB
. functionA(next)
应该能够调用它的函数参数调用next
调用functionB
。
The problem is that I cannot use promises (it would make it a lot easier, unfortunate), so I devised a way like this: 问题是我不能使用诺言(这会使它变得容易得多,不幸的是),所以我设计了这样一种方法:
var functionArray = [functionA, functionB];
functionArray.push(functionC.bind(undefined, args));
for (var i = functionArray.length - 1; i-- > 0; ) {
functionArray[i] = functionArray[i].bind(undefined, args, functionArray[i + 1]);
}
functionArray[0]();
My question is whether or not there is a better way to accomplish this, as the above function looks terribly hacky. 我的问题是,是否有更好的方法来完成此任务,因为上述功能看起来非常骇人。 Maybe something with Array.prototype.reduce ?
也许与Array.prototype.reduce有关系 ?
Why not use a multidimensional array to store the function and it's arguments. 为什么不使用多维数组存储函数及其参数。 This can be cleaned up some but the basic idea is this:
可以清除一些内容,但基本思路是:
var functionArray = [
{ func: yourFunction, args: [1, 2] }
];
for (var i = 0 i < functionArray.length; i++) {
var func = functionArray[i].func;
var args = functionArray[i].args;
func.apply(this, args);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.