CodeBlanks Logo Icon CodeBlanks

Callback hell

Learn callback hell and how to prevent it.

Callback hell

When you nest several callbacks, the code takes a pyramid shape. This is called callback hell; the code becomes hard to read and maintain.

Example: loadUser(id, function (err, user) { loadPosts(user, function (err, posts) { loadComments(posts, function (err, comments) { ... }); }); });. Each call is nested inside the previous callback; the indentation keeps growing.

This pattern is a common problem. Nested callbacks make error handling, flow tracking, and logic hard to maintain. The Node.js community later solved it with promises and async/await; you will see those topics later.

A fix with named functions

One way to reduce callback hell is to use named functions instead of anonymous ones. Moving each step into its own function reduces indentation and makes the code clearer.

Example: loadUser(id, onUser); function onUser(err, user) { loadPosts(user, onPosts); } function onPosts(err, posts) { ... }. Each step now has its own name and body; nesting shrinks.

Named functions also make the stack trace clearer. Still, the most lasting fix is promises and async/await; you will see those in detail at the advanced level.

Practice Two nested calls

Define a function loadUser(id, cb) that calls cb(null, { name: 'Ayşe' }). Then define loadPosts(user, cb) that calls cb(null, ['a', 'b']). Call them nested as loadUser(1, (err, user) => { loadPosts(user, (err2, posts) => { console.log(user.name + ': ' + posts.length); }); }).

Starter code

index.js
// Define loadUser and loadPosts, call them nested

Sample solution

index.js
function loadUser(id, cb) {
  cb(null, { name: 'Ayşe' });
}
function loadPosts(user, cb) {
  cb(null, ['a', 'b']);
}
loadUser(1, (err, user) => {
  loadPosts(user, (err2, posts) => {
    console.log(user.name + ': ' + posts.length);
  });
});

Expected output

Ayşe: 2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the callback hell symptoms

Term Meaning
Pyramid indent Nested structure
Growing depth Indentation keeps increasing
Hard error handling err check at each level
Promise One of the solutions

2 Which is a symptom of callback hell?

  • Nested pyramid indentation Correct answer
  • A one-line function
  • Clean error handling
  • Reduced indentation

Explanation: nested callbacks produce pyramid-shaped indentation.

3 Nested callback

Question
loadUser(id, function (err, user) {
  loadPosts(user, function (____, posts) {
    console.log(posts);
  });
});
Answer
loadUser(id, function (err, user) {
  loadPosts(user, function (err, posts) {
    console.log(posts);
  });
});

Explanation: the inner callback also follows the error-first convention: first parameter is err.

All lessons in Beginner