0

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);
});
22
  • 3
    Possible duplicate of How to handle a duplicate callback? Commented Jun 11, 2019 at 20:32
  • 1
    Besides posting exaclty, word-for-word, duplicate - what is the different issue? Commented Jun 11, 2019 at 20:34
  • 1
    Just as an aside, the runCallbacksInSequence() function is impossible to understand for me. Four nested functions inside a .reduce()? There's no way for me to imagine what the function is trying to do. You might want to simplify your code (or explain it better) in order to get some help. Commented Jun 11, 2019 at 20:45
  • 2
    The nested functions might be a little easier to understand if the parameters had meaningful names. Commented Jun 11, 2019 at 20:55
  • 3
    Are these all really different questions? Commented Jun 11, 2019 at 21:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.