Difference between callbacks and promises in JavaScript:
✅ 1. Definition
- Callback:
- A function passed as an argument to another function, executed after an operation completes.
- Promise:
- An object that represents the eventual success or failure of an asynchronous operation.
✅ 2. Syntax
- Callback:
- Function-based: passed directly into another function.
- Promise:
- Uses
.then()for handling success and.catch()for handling errors.
- Uses
✅ 3. Readability
- Callback:
- Can become messy and hard to read when deeply nested (callback hell).
- Promise:
- More readable, especially when chaining multiple async operations.
✅ 4. Error Handling
- Callback:
- Must handle errors manually at each level (e.g.,
if (err) return ...).
- Must handle errors manually at each level (e.g.,
- Promise:
- Provides a cleaner
.catch()method for centralized error handling.
- Provides a cleaner
✅ 5. Chaining
- Callback:
- Difficult to chain logically; nesting makes it confusing.
- Promise:
- Designed for chaining using
.then(), making sequences of async actions easier to follow.
- Designed for chaining using
✅ 6. Flexibility
- Callback:
- Less flexible; control flow is hard to manage when multiple async tasks depend on each other.
- Promise:
- Offers better control over flow and supports parallel and sequential operations.
✅ 7. Debugging
- Callback:
- Debugging is harder due to nested logic and unclear call stacks.
- Promise:
- Easier to debug because of cleaner and flatter code structure.
✅ 8. Introduction
- Callback:
- Native to JavaScript since the beginning.
- Promise:
- Introduced in ES6 (2015) to solve callback-related problems.
✅ 9. Example
✅ Callback:
function fetchData(callback) {
setTimeout(() => {
callback(null, "Data loaded");
}, 1000);
}
fetchData((err, data) => {
if (err) console.error(err);
else console.log(data);
});
✅ Promise:
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data loaded");
}, 1000);
});
}
fetchData()
.then(data => console.log(data))
.catch(err => console.error(err));
In Summary:
- Use callbacks for simple async tasks.
- Use promises for better structure, readability, and robust error handling in modern JavaScript.