Chapter 19

Controlling the Callback Flow

WHAT’S IN THIS CHAPTER?

  • Understanding the boomerang effect
  • Avoiding deeply nested callbacks
  • Building an asynchronous flow control routine
  • Using async to control callback flow
  • Using async to iterate asynchronously

When Node is performing an asynchronous operation, the result of that operation is not communicated back using the function return value. Instead, asynchronous programming relies on callback functions that are usually passed in as arguments.

When you need to leave your process and do some I/O, most of the time you need to specify a callback function that gets invoked when that operation is finished.

If your task involves a lot of I/O operations, organizing the flow of callback functions can become difficult and may lead to a pattern that is sometimes called “callback soup” or the “boomerang effect.”

UNDERSTANDING THE BOOMERANG EFFECT

The “boomerang effect” happens when a group of callbacks is executed in chain – when one I/O operation completes, the next operation starts. The name “boomerang” derives from the shape of your code when there are many nested callback functions. The increasing left indentation and the return of that indentation makes a boomerang-like shape.

To illustrate the boomerang effect, you’ll build a script that appends bytes 0 to 10 from a file named a.txt into a file named b.txt. Both files exist in the current directory. Listing 19-1 shows an example of the boomerang effect.

LISTING 19-1: A demonstration ...

Get Professional Node.js: Building Javascript Based Scalable Software now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.