I am trying to execute following array (avoid callbackHell) of functions in a sequential order implementing function runCallbacksInSequence (I need to implement
fns.reduceRight((acc, f) => f(acc), cb)
runs
[first, second, third, last].reduceRight((acc, f) => f(acc), second)
which turns into
((acc, f) => f(acc))(
((acc, f) => f(acc))(
((acc, f) => f(acc))(
((acc, f) => f(acc))(
second,
last
),
third
),
second
),
first
)
(because that's what reduceRight does).
The first thing to run is the innermost call,
((acc, f) => f(acc))(
second,
last
)
This becomes
last(second)
which (by the definition of last) is equivalent to
(function () { console.log('last()'); })(second)
This expression ignores second, writes last() to the console, and returns undefined.
This leaves our expression as
((acc, f) => f(acc))(
((acc, f) => f(acc))(
((acc, f) => f(acc))(
undefined,
third
),
second
),
first
)
The next innermost call is
((acc, f) => f(acc))(
undefined,
third
)
which turns into
third(undefined)
By the definition of third this is equivalent to
(function (cb) {
console.log('third()');
cb();
})(undefined)
which in turn executes
console.log('third()');
undefined();
This writes third() to the console, then throws an exception because undefined is not a function.