What is a Callback:
A callback is a function that is passed as an argument to another function and executed later.
Example:
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
function sayBye() {
console.log("Bye!");
}
greet("Bala", sayBye);
Output:
Hello Bala
Bye!
What is Callback Hell:
When callbacks are nested inside other callbacks many times, it becomes hard to read and maintain. This is called Callback Hell.
Example:
setTimeout(() => {
console.log("Step 1");
setTimeout(() => {
console.log("Step 2");
setTimeout(() => {
console.log("Step 3");
setTimeout(() => {
console.log("Step 4");
}, 1000);
}, 1000);
}, 1000);
}, 1000);
This code looks like a pyramid shape.
This is called Callback Hell or Pyramid of Doom.
Problems in Callback Hell:
*Hard to read
*Hard to debug
*Hard to maintain
*Error handling is difficult
What is a Promise:
A Promise is used to handle asynchronous operations in a better way.
A Promise has 3 states:
Pending
Resolved (Success)
Rejected (Error)
Promise Example:
let promise = new Promise(function(resolve, reject) {
let success = true;
if (success) {
resolve("Task completed");
} else {
reject("Task failed");
}
});
promise
.then(function(result) {
console.log(result);
})
.catch(function(error) {
console.log(error);
});
Callback Hell vs Promise:
| Callback Hell | Promise |
|---|---|
| Nested callbacks | Chain using .then()
|
| Hard to read | Easy to read |
| Hard to maintain | Easy to maintain |
| Error handling difficult | Error handling easy with .catch()
|
Promise States Diagram:
Draw a simple flow:
[Pending]
/ \
/ \
[Resolved] Rejected (Error)
Real-World Example Diagram:
Use a food order example
CallbackHell:
Order Food
↓
Prepare Food
↓
Pack Food
↓
Deliver Food
Promise:
Order → Prepare → Pack → Deliver
You can end your blog like this:
",Callback Hell makes code messy. Promises make code clean, readable, and easy to manage."
Top comments (0)