JavaScript Internals (521 Qs)•Part 2: Promises, Callbacks, Async & Strict Mode (54 - 103)
Why do you need a promise
Promises are used to handle asynchronous operations, especially in languages like JavaScript, which often work with non-blocking operations such as network requests, file I/O, and timers. When an operation is asynchronous, it doesn't immediately return a result; instead, it works in the background and provides the result later. Handling this in a clean, organized way can be difficult without a structured approach.
Promises are used to:
- Handle asynchronous operations.
- Provide a cleaner alternative to callbacks.
- Avoid callback hell.
- Make code more readable and maintainable.
Practical Code Example
javascript
// Before Promises: Callback Hell / Pyramid of Doom
getUser(id, (user) => {
getOrders(user.id, (orders) => {
getOrderDetails(orders[0].id, (details) => {
console.log(details);
});
});
});
// With Promises: Linear, composable, clean error handling
getUser(id)
.then((user) => getOrders(user.id))
.then((orders) => getOrderDetails(orders[0].id))
.then((details) => console.log(details))
.catch((err) => console.error('Caught error anywhere in chain:', err));