
When working with JavaScript, you will often deal with operations that do not finish immediately. For example, fetching data from an API, reading a file in Node.js, querying a database, or uploading an image to cloud storage can take some time.
In these situations, JavaScript allows us to use callbacks to execute code after an operation finishes.
Callbacks are useful, but things can become difficult when one asynchronous operation depends on the result of another. As the number of dependent operations increases, callbacks can become deeply nested, making the code harder to read, debug, and maintain.
This problem is commonly known as callback hell.
I have seen how quickly asynchronous code can become complicated when a single workflow involves several operations. A simple process such as logging in a user, fetching their profile, loading their permissions, and retrieving their dashboard data can turn into a confusing structure if every step depends on nested callbacks.
In this article, I'll explain what callback hell is, why it happens, how to recognize it, and how we can avoid it using practical JavaScript examples.
What Is Callback Hell in JavaScript?
Callback hell occurs when multiple callback functions are nested inside one another, usually because several asynchronous operations must execute in a particular order.
As the nesting increases, the code starts moving toward the right side of the editor. This is why developers sometimes call it the pyramid of doom.
Let's start with a simple example.
Imagine that we are building an application where a user places an order. To complete the process, we need to:
Fetch the user's details.
Check whether the product is available.
Process the payment.
Create the order.
Send a confirmation email.
Each step depends on the previous operation succeeding.
Using callbacks, the code might look like this:
function getUser(userId, callback) {
setTimeout(() => {
callback(null, {
id: userId,
name: "Manjeet",
});
}, 500);
}
function checkProduct(productId, callback) {
setTimeout(() => {
callback(null, {
id: productId,
name: "Laptop",
price: 50000,
});
}, 500);
}
function processPayment(amount, callback) {
setTimeout(() => {
callback(null, {
transactionId: "TXN123",
amount,
});
}, 500);
}
function createOrder(user, product, payment, callback) {
setTimeout(() => {
callback(null, {
orderId: "ORD101",
userId: user.id,
productId: product.id,
transactionId: payment.transactionId,
});
}, 500);
}
function sendConfirmationEmail(order, callback) {
setTimeout(() => {
callback(null, `Confirmation sent for ${order.orderId}`);
}, 500);
}
getUser(1, (error, user) => {
if (error) {
console.error(error);
return;
}
checkProduct(101, (error, product) => {
if (error) {
console.error(error);
return;
}
processPayment(product.price, (error, payment) => {
if (error) {
console.error(error);
return;
}
createOrder(user, product, payment, (error, order) => {
if (error) {
console.error(error);
return;
}
sendConfirmationEmail(order, (error, message) => {
if (error) {
console.error(error);
return;
}
console.log(message);
});
});
});
});
});The example demonstrates the problem clearly.
Every operation is nested inside the callback of the previous operation. We also have to repeat error handling at every level.
As we add more business logic, the code becomes harder to follow.
Imagine opening a real backend project and finding ten or fifteen nested callbacks in a single function. Understanding the workflow or identifying where an error occurs can take much longer than necessary.
That is the main problem with callback hell.
Important: Callbacks themselves are not bad. The problem is excessive nesting and poorly structured asynchronous control flow.
Why Does Callback Hell Happen?
There are several reasons why callback hell appears in JavaScript applications.
1. Multiple asynchronous operations depend on each other
Suppose you need to fetch a user from MongoDB and then use that user's ID to fetch their orders.
The second operation cannot begin until the first operation returns the required information.
When every function uses callbacks, each dependent operation may need to be placed inside another callback.
For example:
getUser(userId, (error, user) => {
if (error) {
return console.error(error);
}
getOrders(user.id, (error, orders) => {
if (error) {
return console.error(error);
}
getOrderDetails(orders[0].id, (error, details) => {
if (error) {
return console.error(error);
}
console.log(details);
});
});
});Each operation adds another level of nesting.
2. Error handling gets repeated
In callback-based code, developers often use an error-first callback convention.
For example:
function fetchData(callback) {
// The callback receives an error and a result.
callback(null, { message: "Data loaded" });
}The first argument represents an error, while the second represents the successful result.
When several operations are nested, each callback needs to check for errors.
if (error) {
return console.error(error);
}Repeating this pattern across many nested functions makes the code longer and can make it harder to maintain consistent error handling.
3. Business logic becomes difficult to understand
Consider a checkout process that involves inventory validation, payment processing, order creation, and notifications.
When all these steps are deeply nested, it becomes difficult to identify the main workflow.
Instead of seeing a clear sequence of operations, you must mentally navigate through several callback levels.
This can make debugging and future modifications more difficult.
4. Reusing asynchronous logic becomes harder
When operations are tightly coupled inside nested callbacks, reusing individual steps can require extra work.
For example, you might want to reuse the same payment verification logic in both a checkout flow and a subscription renewal process.
Separating operations into independent functions helps, but the overall asynchronous flow still needs a clean structure.
This is one reason modern JavaScript code commonly uses Promises and async/await.
How to Avoid Callback Hell Using Named Functions
Before moving to Promises, let's look at a simpler way to improve callback-based code.
One option is to move nested callback logic into separate named functions.
Instead of defining every callback inline, we can create functions for individual steps.
function handleUser(error, user) {
if (error) {
return console.error("User error:", error);
}
checkProduct(101, (error, product) => {
handleProduct(error, user, product);
});
}
function handleProduct(error, user, product) {
if (error) {
return console.error("Product error:", error);
}
processPayment(product.price, (error, payment) => {
handlePayment(error, user, product, payment);
});
}
function handlePayment(error, user, product, payment) {
if (error) {
return console.error("Payment error:", error);
}
createOrder(user, product, payment, (error, order) => {
if (error) {
return console.error("Order error:", error);
}
console.log("Order created:", order);
});
}
getUser(1, handleUser);This approach gives each function a meaningful name and reduces the amount of nested code inside the main entry point.
However, there is a limitation: the callbacks are still connected manually, and the flow can become complicated as more operations are added.
Named functions can improve existing callback-based code, but they do not solve every problem associated with asynchronous control flow.
For many modern JavaScript applications, Promises offer a more convenient solution.
Avoiding Callback Hell with Promises
Promises provide a structured way to represent the eventual result of an asynchronous operation.
Instead of passing a callback into every function, we can return a Promise and connect the operations using .then().
Let's revisit the order-processing example.
First, we will convert the functions to return Promises.
function getUser(userId) {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
id: userId,
name: "Manjeet",
});
}, 500);
});
}
function checkProduct(productId) {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
id: productId,
name: "Laptop",
price: 50000,
});
}, 500);
});
}
function processPayment(amount) {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
transactionId: "TXN123",
amount,
});
}, 500);
});
}
function createOrder(user, product, payment) {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
orderId: "ORD101",
userId: user.id,
productId: product.id,
transactionId: payment.transactionId,
});
}, 500);
});
}These examples simulate asynchronous operations with setTimeout(). In a real application, the functions would call a database, payment provider, or another service.
Now we can connect them.
getUser(1)
.then((user) => {
return checkProduct(101).then((product) => {
return processPayment(product.price).then((payment) => {
return createOrder(user, product, payment);
});
});
})
.then((order) => {
console.log("Order created:", order);
})
.catch((error) => {
console.error("Order processing failed:", error.message);
});Although this code uses Promises, we still have some unnecessary nesting.
We can improve it by storing the intermediate values or using a flatter Promise chain. However, because later operations depend on values from earlier steps, we must preserve those values somehow.
One option is to return the accumulated data from each step.
getUser(1)
.then((user) => {
return checkProduct(101).then((product) => ({
user,
product,
}));
})
.then(({ user, product }) => {
return processPayment(product.price).then((payment) => ({
user,
product,
payment,
}));
})
.then(({ user, product, payment }) => {
return createOrder(user, product, payment);
})
.then((order) => {
console.log("Order created:", order);
})
.catch((error) => {
console.error("Order processing failed:", error.message);
});Now the operations are connected through a Promise chain, and a single .catch() can handle rejections that propagate through that chain.
This is already more structured than deeply nested callbacks.
Still, carrying values through multiple Promise handlers can become verbose. There is another syntax that makes this workflow easier to read.
The Best Solution for Many Workflows: Async/Await
The async/await syntax was introduced to make working with Promises more readable.
It allows us to write asynchronous code in a style that resembles ordinary sequential JavaScript.
An async function always returns a Promise. Inside it, await pauses that function's execution until the awaited Promise settles. It does not block the JavaScript thread while waiting for the asynchronous operation.
Let's rewrite the order-processing workflow using async/await.
async function placeOrder() {
try {
const user = await getUser(1);
const product = await checkProduct(101);
const payment = await processPayment(product.price);
const order = await createOrder(
user,
product,
payment
);
console.log("Order created:", order);
} catch (error) {
console.error("Order processing failed:", error.message);
}
}
placeOrder();This version is easier to understand because the main steps are written one after another.
We can read the function almost like a set of instructions:
Get the user.
Check the product.
Process the payment.
Create the order.
Handle any errors.
There is no deeply nested callback structure, and the error handling is centralized in a try...catch block.
For many backend workflows in Node.js and frontend operations in React or Next.js, this is a clean and practical approach.
Why does async/await make the code easier to read?
The biggest advantage is that it separates the main workflow from the mechanics of handling asynchronous results.
With callbacks, each step receives a function that must execute when the operation finishes.
With async/await, each step can return a Promise, and the caller can wait for its result using await.
This makes it easier to:
Follow the execution order.
Read and modify business logic.
Handle errors with
try...catch.Debug individual operations.
Keep asynchronous functions reusable.
One thing to remember is that async/await does not eliminate Promises. It is built on top of them.
If an awaited Promise rejects, the await expression throws that rejection reason, allowing a surrounding try...catch block to handle it.
Avoiding Callback Hell in Node.js File Operations
Callback hell is especially easy to encounter in Node.js when working with older callback-based APIs.
For example, suppose we want to read a configuration file, parse its JSON content, and extract a database connection setting.
Using the traditional callback-based fs.readFile() API, the code might look like this:
const fs = require("node:fs");
fs.readFile("config.json", "utf8", (error, content) => {
if (error) {
return console.error("File reading failed:", error);
}
let config;
try {
config = JSON.parse(content);
} catch (parseError) {
return console.error("Invalid JSON:", parseError);
}
console.log("Database URL:", config.databaseUrl);
});This example does not contain severe callback hell because it has only one asynchronous callback. However, imagine adding more asynchronous operations inside it, such as reading another file or fetching additional configuration from a service.
The nesting could increase quickly.
For modern Node.js applications, we can use the Promise-based file system API.
const fs = require("node:fs/promises");
async function loadConfig() {
try {
const content = await fs.readFile("config.json", "utf8");
const config = JSON.parse(content);
console.log("Database URL:", config.databaseUrl);
} catch (error) {
console.error("Unable to load configuration:", error.message);
}
}
loadConfig();This version is shorter and easier to extend.
If we later need to read another file, validate the configuration, or call an API, we can add those steps without creating deeply nested callbacks.
The node:fs/promises module provides Promise-based versions of many common file system operations, making it a useful option for modern Node.js development.
Avoiding Callback Hell in Express.js
Let's look at a backend example.
Suppose we are building an Express.js API that retrieves a user and then loads that user's orders.
In older callback-based code, the route handler might become nested as more database operations are added.
With async/await, the route can remain straightforward.
app.get("/users/:id/orders", async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).json({
success: false,
message: "User not found",
});
}
const orders = await Order.find({
userId: user._id,
});
return res.status(200).json({
success: true,
user,
orders,
});
} catch (error) {
console.error("Failed to fetch user orders:", error);
return res.status(500).json({
success: false,
message: "Internal server error",
});
}
});This example assumes that User and Order are database models available in the application.
The route first retrieves the user. If the user does not exist, it returns a 404 response. Otherwise, it fetches the associated orders and returns them.
A single try...catch handles errors from the awaited operations.
There is no need to nest a database callback inside another database callback.
Production note: In Express 5, rejected Promises returned by route handlers and middleware are automatically passed to error-handling middleware. In Express 4, you generally need to forward rejected Promises to next(error) or use a suitable async-handler wrapper. The exact approach depends on the Express version and the application's error-handling setup.
This is a practical example of how modern asynchronous syntax can improve the readability of a backend API.
What About Operations That Can Run in Parallel?
Not every asynchronous operation needs to wait for the previous one.
Sometimes, two or more operations are independent and can run at the same time.
For example, a dashboard might need to fetch a user's notifications and their recent activity. If neither request depends on the result of the other, waiting for the first request before starting the second is unnecessary.
Consider this example:
async function loadDashboard(userId) {
const notifications = await getNotifications(userId);
const activities = await getRecentActivities(userId);
return {
notifications,
activities,
};
}Here, the second operation begins only after the first awaited operation finishes.
If both functions return Promises and the operations are independent, we can use Promise.all().
async function loadDashboard(userId) {
try {
const [notifications, activities] = await Promise.all([
getNotifications(userId),
getRecentActivities(userId),
]);
return {
notifications,
activities,
};
} catch (error) {
console.error("Unable to load dashboard:", error.message);
throw error;
}
}Both operations are started before Promise.all() is awaited, so they can make progress concurrently.
This approach can reduce the total waiting time when the operations are genuinely independent.
However, do not use parallel execution when one operation requires the result of another. For example, you cannot fetch a user's orders using their database ID until you have obtained that ID.
Also, Promise.all() rejects when one of its input Promises rejects, but it does not automatically cancel the other operations.
Understanding the difference between sequential and concurrent execution helps you avoid unnecessary waiting without breaking dependencies.
Best Practices to Avoid Callback Hell
Based on these patterns, here are some practical guidelines for writing cleaner asynchronous JavaScript.
1. Prefer Promises for asynchronous workflows
When an API supports Promises, use them instead of introducing additional callback layers.
Promises make it easier to connect operations, return results, and propagate errors.
2. Use async/await when it improves readability
For workflows with several dependent operations, async/await often provides the clearest structure.
It allows you to write the main logic sequentially while still working asynchronously.
3. Keep functions focused on one responsibility
Avoid putting every step of a large workflow inside one function.
For example, a checkout process might have separate functions for validating inventory, processing payment, creating an order, and sending a notification.
Smaller functions are easier to test and maintain.
4. Handle errors at the appropriate level
Do not repeat the same error-handling logic in every function if the caller can handle the failure appropriately.
Let errors propagate when necessary, and catch them where you can recover or provide a meaningful response.
However, handle errors locally when a particular operation requires a specific recovery strategy.
5. Return Promises from Promise handlers
When you start an asynchronous operation inside .then(), return its Promise if the next step needs to wait for it.
For example:
getUser(1)
.then((user) => {
return getOrders(user.id);
})
.then((orders) => {
console.log(orders);
})
.catch((error) => {
console.error(error);
});Returning the Promise ensures that its outcome becomes part of the chain.
6. Do not make independent operations sequential unnecessarily
Use Promise.all() when multiple operations are independent and you need all their results.
This can improve response times in applications that fetch several pieces of data for the same page.
7. Avoid wrapping every function in a new Promise
A common mistake is creating a new Promise around an operation that already returns one.
For example, avoid unnecessary wrappers like this:
function getUser() {
return new Promise((resolve, reject) => {
fetchUserFromDatabase()
.then(resolve)
.catch(reject);
});
}If fetchUserFromDatabase() already returns a Promise and you do not need to add any extra behavior, you can simply return it:
function getUser() {
return fetchUserFromDatabase();
}This keeps the implementation simpler and avoids unnecessary code.
Conclusion
Callback hell is a common JavaScript problem that appears when multiple callbacks become deeply nested, particularly when several asynchronous operations depend on each other.
Although callbacks are still useful, excessive nesting can make code difficult to read, maintain, and debug.
There are several ways to improve this situation:
Use named functions to organize existing callback-based code.
Use Promises to connect asynchronous operations through
.then()and.catch().Prefer
async/awaitfor workflows that are easier to understand as sequential steps.Use
try...catchto handle errors in asynchronous functions.Use
Promise.all()when independent operations can run concurrently.Keep functions small, reusable, and focused on a single responsibility.
For modern Node.js, React, and Next.js development, I generally recommend understanding both Promises and async/await. They help you write asynchronous code that is easier to understand and maintain as your application grows.
The main lesson is simple: the goal is not to avoid callbacks completely, but to structure asynchronous code so that its execution flow remains clear.
Once you understand when to use callbacks, Promises, and async/await, handling asynchronous operations becomes much more manageable.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


