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).
Here is what I have so far. The function runCallbacksInSequence
works well till it gets the same callback cb(null, 'one');
the second time. Ideally if it gets the same callback more than once it should not execute it second time and ignore it.
If you have any ideas let me know how I can implement it. - no promises and async/await
function first(cb) {
setTimeout(function() {
console.log('first()');
cb(null, 'one');
cb(null, 'one');//not supposed to be execute by runCallbacksInSequence
}, 0);
}
function last(cb) {
console.log('last()');
cb(null, 'lastCall');
}
function runCallbacksInSequence(fns, cb) {
fns.reduce(
(r, f) => {
return k => {
return r(() => {
return f((e, x) => {
return e ? cb(e) : k(x);
});
});
};
},
k => {
return k();
}
)(r => {
return cb(null, r);
});
}
fns = [first, last];
runCallbacksInSequence(fns, function(err, results) {
if (err) return console.log('error: ' + err.message);
console.log(results);
});