Hello all...today I will be telling about callback functions in Javascript. A callback function is a function which is passed as an argument to another function and is executed once the parent function completes its execution. This is especially useful for asynchronous operations like API calls , timers or event handling. The reason why we use callback functions is because:
- They allow asynchronous behaviour in a single-threaded language (meaning the code is executed line by line and only after the current line is executed ,the next line starts executing).
2.They're essential for tasks like loading data, handling user input, or animations.
Example:
function greetUser(name, callback) {
console.log("Hello, " + name + "!");
callback(); // Call the function passed in
}
function sayGoodbye() {
console.log("Goodbye!");
}
greetUser("Ranjani", sayGoodbye);
//Output
Hello, Ranjani!
Goodbye!
Next let's talk about Callback Hell also known as Pyramid of Doom. Callback hell happens when callbacks are nested within callbacks, creating deeply indented, hard-to-read code. This often occurs when multiple asynchronous tasks depend on each other. The problems with callback hell are
- Poor readability and maintainability
- Difficult to Debug
- Inversion of control (we lose control over the flow of the program).
Example:
function task1(callback) {
setTimeout(() => {
console.log("Task 1 completed");
callback();
}, 1000);
}
function task2(callback) {
setTimeout(() => {
console.log("Task 2 completed");
callback();
}, 1000);
}
function task3(callback) {
setTimeout(() => {
console.log("Task 3 completed");
callback();
}, 1000);
}
// Nested callbacks — the pyramid begins
task1(() => {
task2(() => {
task3(() => {
console.log("All tasks completed");
});
});
});
Output:
Task 1 completed
Task 2 completed
Task 3 completed
All tasks completed
In the above code, it becomes really hard to follow due to deep nesting of elements, errors are hard to find and correct and also adding or modifying logic becomes very difficult. Hence in order to avoid this type of scenarios we go for a modern solution known as Promises.
A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation. It helps flatten nested callbacks and makes code more readable. It has the following states and methods:
- Pending: Initial state
- Fulfilled: Operation completed successfully
- Rejected: Operation failed
- .then() — handles success
- .catch() — handles errors
- .finally() — runs regardless of outcome
So that's it about callbacks, callback hell and promises. Will talk in more detail about promises in the next post.
Top comments (0)