JavaScript
Managing callbacks
Learn to make nested callbacks manageable by splitting them into named functions.
Splitting into named functions
The simplest way to fix callback hell is to split nested callbacks into named functions. You define each step as its own function; indentation shrinks and each function has a single task.
function loadUser() {
loadPosts();
}
function loadPosts() {
loadComments();
}
function loadComments() {
console.log('Done');
}
This approach makes the code more readable. Error handling can also be done separately inside each function. This pattern is called modularization.
Before and after
You can write the same flow in two ways. First, the callback hell form:
step1(() => {
step2(() => {
step3(() => {});
});
});
Now with named functions:
function onStep1() {
step2(onStep2);
}
function onStep2() {
step3(onStep3);
}
function onStep3() {
console.log('Done');
}
Each function is short and single-tasked; you can read the flow top to bottom.
Exercise Write three named functions
Define three named functions: step1, step2 and step3. Inside step1, use setTimeout to call step2 after 100 ms. Inside step2, use setTimeout to call step3 after 100 ms. Inside step3, print a short message with console.log. Pass the functions by name, without parentheses.
Show example solution
function step1() {
setTimeout(step2, 100);
}
function step2() {
setTimeout(step3, 100);
}
function step3() {
console.log('Done');
}
Test yourself
-
What is the main benefit of splitting nested callbacks into named functions?
- Readability improves, tasks are separated
- Less code is written
- Code runs faster
- Errors disappear completely
Show answer
Readability improves, tasks are separated — Correct! Each function has a single task; the flow reads top to bottom.
-
Call the named callback
function onStep1() {
step2(____);
}
Show answer
function onStep1() {
step2(onStep2);
}
-
Match the concepts
- named function
- Separates tasks
- modularization
- Splitting approach
- indentation
- Decreases
- onStep1
- First step
-
When should you split nested callbacks into named functions?
- Never
- Only when there is an error
- When nesting goes beyond 2 levels
- Only in synchronous code
Show answer
When nesting goes beyond 2 levels — Correct! Splitting keeps readability when nesting deepens beyond 2 levels.
Next lesson: Summary - Callbacks