4 min read
•Question 27 of 62mediumWhat is Callback Hell and how to avoid it?
Understanding callback hell and solutions.
What You'll Learn
- What callback hell is
- Why it's problematic
- How to avoid it
What is Callback Hell?
Callback Hell (Pyramid of Doom) occurs when you have nested callbacks, making code hard to read and maintain.
Example of Callback Hell
code.jsJavaScript
// ❌ Callback Hell
getUser(userId, (err, user) => {
if (err) handleError(err);
getOrders(user.id, (err, orders) => {
if (err) handleError(err);
getOrderDetails(orders[0].id, (err, details) => {
if (err) handleError(err);
getProduct(details.productId, (err, product) => {
if (err) handleError(err);
console.log(product);
});
});
});
});Solutions
1. Promises
code.jsJavaScript
getUser(userId)
.then(user => getOrders(user.id))
.then(orders => getOrderDetails(orders[0].id))
.then(details => getProduct(details.productId))
.then(product => console.log(product))
.catch(handleError);2. Async/Await
code.jsJavaScript
async function getData(userId) {
try {
const user = await getUser(userId);
const orders = await getOrders(user.id);
const details = await getOrderDetails(orders[0].id);
const product = await getProduct(details.productId);
console.log(product);
} catch (error) {
handleError(error);
}
}