Error Handling Executing Callbacks In Sequential Order
I am trying to execute following array (avoid callbackHell) of functions in a sequential order implementing function runCallbacksInSequence (I need to implement my own function to
Solution 1:
SOLUTION
The following solution will handle the errors and the async behavior
functionfirst(cb) {
setTimeout(function() {
console.log('first()');
cb(null, 'one');
}, 0);
}
functionsecond(cb) {
setTimeout(function() {
console.log('second()');
cb(null, 'two');
}, 100);
}
functionthird(cb) {
setTimeout(function() {
console.log('third()');
cb(null, 'three');
}, 0);
}
functionlast(cb) {
console.log('last()');
cb(null, 'lastCall');
// cb(new Error('Invalid object'), null);
}
functionrunCallbacksInSequence(fns, cb) {
fns.reduce(
(r, f) =>k =>r(acc =>f((e, x) => (e ? cb(e) : k([...acc, x])))),
k =>k([])
)(r =>cb(null, r));
}
const fns = [first, second, third, last];
runCallbacksInSequence(fns, function(err, results) {
if (err) returnconsole.log('error: ' + err.message);
console.log(...results);
});
Post a Comment for "Error Handling Executing Callbacks In Sequential Order"