简体   繁体   中英

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 .

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 ?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM