tarabyte
tarabyte

Reputation: 19172

How to cleanly structure multiple asynchronous calls in javascript?

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?

Upvotes: 0

Views: 31

Answers (1)

cybersam
cybersam

Reputation: 67009

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

Upvotes: 2

Related Questions