Skip to content Skip to sidebar Skip to footer

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

    function first(cb) {
      setTimeout(function() {
        console.log('first()');
        cb(null, 'one');
      }, 0);
    }
    function second(cb) {
      setTimeout(function() {
        console.log('second()');
        cb(null, 'two');
      }, 100);
    }
    function third(cb) {
      setTimeout(function() {
        console.log('third()');
        cb(null, 'three');
      }, 0);
    }
    function last(cb) {
      console.log('last()');
      cb(null, 'lastCall');
      // cb(new Error('Invalid object'), null);
    }

    function runCallbacksInSequence(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) return console.log('error: ' + err.message);
      console.log(...results);
    });

Post a Comment for "Error Handling Executing Callbacks In Sequential Order"