Callback Hell — Code Smells Catalog Skip to content

Callback Hell

Also known as: Hierarchy of Callbacks, Pyramid of Doom

Change Preventers Conditional Logic Code Smell Within Class

Nested callbacks indented so deep the closing brackets cascade like a staircase to nowhere. The actual logic hides somewhere around indent level five.

2 min read 1 source

Overview

Smell with a scent similar to the Conditional Complexity, where tabs are intended deep, and the curly closing brackets can cascade like a Niagara waterfall.

The callback is a function that is passed into another function as an argument that is meant to be executed later. One of the most popular callbacks could be the addEventListener in JavaScript.

Alone in separation, they are not causing or indicating any problems. Instead, the long list of chained callbacks is something to watch out for. More professionally, this could be called a Hierarchy of Callbacks but (fortunately), it has already received a more exciting and recognizable name. There are many solutions to this problem: Promises, async functions, or splitting the significant function into separate methods.

Problems

📖
Comprehensibility

Long and deep nested methods are challenging to read and maintain.

Inversion of Control Violation

One shouldn't give up control of how things are used.

Example

1const makeSandwich = () => {
2  ...
3  getBread(function(bread) {
4    ...
5    sliceBread(bread, function(slicedBread) {
6      ...
7      getJam(function(jam) {
8        ...
9        brushBread(slicedBread, jam, function(smearedBread) {
10          ...
11        });
12      });
13    });
14  });
15};
JAVASCRIPT

Refactoring

  • Extract Methods
  • Use Asynchronous Functions
  • Use Promises

Sources

Browse All 56 Smells