0

I'm just getting used to callbacks in javascript, but quickly found my code getting unwieldy and think there's a smarter way to approach this.

I have a process, let's call it doAaBbCc() that has three subprocesses:

var doAa = function(onAaCompleted) {
  // Do something slow
  onAaCompleted(true);
};

var doBb = function(onBbCompleted) {
  // Do something slow
  onBbCompleted(true);
};

var doCc = function(onCcCompleted) {
  // Do something slow
  onCcCompleted(false);
};

var onAaBbCcCompleted = function(succeeded) {
  console.log('Did doAaBbCc() complete successfully?: ' + succeeded);
};

/// @brief Performs A, B and C, stopping at first failure
/// @param[in] onAaBbCcCompleted, Called on completion of this method.
///                               Passes whether overall operation succeeded.
var doAaBbCc = function(onAaBbCcCompleted) {
  // Beginning of strangeness
  doAa(function(aSucceeded) {
    if (!aSucceeded) {
      onAaBbCcCompleted(aSucceeded);
    }
    doBb(function(bSucceeded) {
      if (!bSucceeded) {
        onAaBbCcCompleted(bSucceeded);
      }
      doCc(function(cSucceeded) {
        onAaBbCcCompleted(cSucceeded);
      });
    });
  });
};

Each subprocess can fail and I'm not quite sure how to bubble up that error and/or provide a way for the passed in callback to react to a success different from a failure. Each subprocess also needs to call itself a handful of times to finish its process.

I guess what I'm asking is, is there a JavaScript-best-practice way to approach this?

2
  • 2
    How about Futures and Promises? Commented Dec 17, 2014 at 0:35
  • Wow, it looks like they even chose very similar method names. Commented Dec 17, 2014 at 0:37

1 Answer 1

2

What you are describing is a common problem popularly termed "callback hell". A popular utility for addressing it is async.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.