I am trying to execute following array (avoid callbackHell) of functions in a sequential order implementing function runCallbacksInSequence (I need to implement
Have the .reduce callback be a higher-order function, which, when called, calls the next function in the chain with the callback. At the end, you'll have a function chain that will start by calling the first function, then the second, etc:
function first(cb) {
console.log('first()');
cb();
}
function second(cb) {
console.log('second()');
cb();
}
function third(cb) {
console.log('third()');
cb();
}
function last() {
console.log('last()');
}
let fns = [first, second, third, last];
function runCallbacksInSequence(fns, cb) {
const chainedFns = fns.reduceRight((acc, f) => () => f(acc), cb);
return chainedFns();
}
runCallbacksInSequence(fns);
If you wanted the runCallbacksInSequence to accept another callback to run at the end of all of them, then:
function first(cb) {
console.log('first()');
cb();
}
function second(cb) {
console.log('second()');
cb();
}
function third(cb) {
console.log('third()');
cb();
}
function last(cb) {
console.log('last()');
cb();
}
let fns = [first, second, third, last];
function runCallbacksInSequence(fns, cb) {
const chainedFns = fns.reduceRight((acc, f) => () => f(acc), cb);
return chainedFns();
}
runCallbacksInSequence(fns, () => console.log('outer call'));