Callback Best Practices: Callback Discipline

Learn about callback discipline with an example.

Now that we’ve met our first example of callback hell, we know what we should definitely avoid; however, that’s not the only concern when writing asynchronous code. In fact, there are several situations where controlling the flow of a set of asynchronous tasks requires the use of specific patterns and techniques, especially if we’re only using plain JavaScript without the aid of any external library. For example, iterating over a collection by applying an asynchronous operation in sequence is not as easy as invoking the forEach() function over an array; it actually requires a technique similar to recursion.

In this section, we’ll learn not only about how to avoid callback hell but also how to implement some of the most common control flow patterns, using only simple and plain JavaScript.

Callback discipline

When writing asynchronous code, the first rule to keep in mind is to not misuse in-place function definitions when defining callbacks. It can be tempting to do so because it doesn’t require any additional thinking for problems such as modularization and reusability; however, we have seen how this can have more disadvantages than advantages. Most of the time, fixing the callback hell problem doesn’t require any libraries, fancy techniques, or changes of paradigm; we just need some common sense.

These are some basic principles that can help us keep the nesting level low and improve the organization of our code in general:

  • Exit as soon as possible. Use return, continue, or break, depending on the context, to immediately exit the current statement instead of writing (and nesting) complete if...else statements. This will help to keep our code shallow.

  • Create named functions for callbacks, keeping them out of closures and passing intermediate results as arguments. Naming our functions will also make them look better in stack traces.

  • Modularize the code. Split the code into smaller, reusable functions whenever possible.

Now, let’s put these principles into practice.

Applying the callback discipline

To demonstrate the power of the ideas mentioned in the previous section, let’s apply them to fix the callback hell in our web spider application.

For the first step, we can refactor our error-checking pattern by removing the else statement. This is made possible by returning from the function immediately after we receive an error. So, instead of having code such as the following:

Get hands-on with 1200+ tech skills courses.