I am trying to execute following array (avoid callbackHell) of functions(sync/async), in a sequential order, implementing function runCallbacksInSequence (I need to implement my own function to understand how callbacks work and avoid using Async.js).
I do not quite understand how callbacks work that is why I am doing this exercise. Here is what I have so far. The function runCallbacksInSequence works well but I am having hard time to implement callback (null, result) signature. At the moment it follows callback (result) signature.
If you have any ideas let me know what I am doing wrong and how I can fix it.
- no promises and async/await
function first(cb) {
setTimeout(function() {
console.log('first()');
cb('one');
// cb(null, 'one');
}, 0);
}
function second(cb) {
setTimeout(function() {
console.log('second()');
cb('two');
// cb(null, 'two');
}, 100);
}
function third(cb) {
setTimeout(function() {
console.log('third()');
cb('three');
// cb(null, 'three');
}, 0);
}
function last(cb) {
console.log('last()');
cb('lastCall');
// cb(null, 'lastCall');
}
function runCallbacksInSequence(fns, cb) {
fns.reduce((r, f) => k => r(acc => f(x => k([...acc, x]))), k => k([]))(cb);
}
const fns = [first, second, third, last];
runCallbacksInSequence(fns, results => {
console.log('-- DONE --');
console.log(...results);
});