Node.js
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.
Exercise 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); }); }).
Show example solution
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);
});
});
Test yourself
-
Match the callback hell symptoms
- Pyramid indent
- Nested structure
- Growing depth
- Indentation keeps increasing
- Hard error handling
- err check at each level
- Promise
- One of the solutions
-
Which is a symptom of callback hell?
- Nested pyramid indentation
- A one-line function
- Clean error handling
- Reduced indentation
Show answer
Nested pyramid indentation — nested callbacks produce pyramid-shaped indentation.
-
Nested callback
loadUser(id, function (err, user) {
loadPosts(user, function (____, posts) {
console.log(posts);
});
});
Show answer
loadUser(id, function (err, user) {
loadPosts(user, function (err, posts) {
console.log(posts);
});
});
Next lesson: Summary - Callbacks