Skip to content

How to Fix Node.js Callback Hell with Async/Await

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about How to Fix Node.js Callback Hell with Async/Await. We cover key concepts, practical examples, and best practices.

The Problem

Node.js callback hell (also called the pyramid of doom) occurs when multiple nested callbacks create deeply indented, hard-to-read, and error-prone code when performing sequential asynchronous operations.

Quick Fix

Step 1: Identify the callback nesting

const fs = require('fs');

fs.readFile('user.json', 'utf8', (err, data) => {
    if (err) return console.error(err);
    const user = JSON.parse(data);
    fs.readFile(`orders-${user.id}.json`, 'utf8', (err, orders) => {
        if (err) return console.error(err);
        const parsedOrders = JSON.parse(orders);
        fs.readFile(`items-${parsedOrders[0].id}.json`, 'utf8', (err, items) => {
            if (err) return console.error(err);
            console.log(JSON.parse(items));
        });
    });
});

This is callback hell: deeply nested, hard to debug, and repetitive error handling.

Step 2: Convert callbacks to promises

Use util.promisify to convert callback-based functions:

const fs = require('fs');
const { promisify } = require('util');
const readFile = promisify(fs.readFile);

readFile('user.json', 'utf8')
    .then(data => JSON.parse(data))
    .then(user => readFile(`orders-${user.id}.json`, 'utf8'))
    .then(orders => JSON.parse(orders))
    .then(parsedOrders => readFile(`items-${parsedOrders[0].id}.json`, 'utf8'))
    .then(items => console.log(JSON.parse(items)))
    .catch(err => console.error(err));

Step 3: Use async/await for linear code

The final transformation:

const fs = require('fs');
const { promisify } = require('util');
const readFile = promisify(fs.readFile);

async function loadOrderItems() {
    try {
        const userData = await readFile('user.json', 'utf8');
        const user = JSON.parse(userData);
        const ordersData = await readFile(`orders-${user.id}.json`, 'utf8');
        const orders = JSON.parse(ordersData);
        const itemsData = await readFile(`items-${orders[0].id}.json`, 'utf8');
        const items = JSON.parse(itemsData);
        console.log(items);
    } catch (err) {
        console.error('Failed to load order items:', err);
    }
}

loadOrderItems();

Step 4: Use Promise.all for parallel operations

Independent calls should run in parallel:

async function loadBatch() {
    try {
        const [users, products, categories] = await Promise.all([
            fetchUsers(),
            fetchProducts(),
            fetchCategories()
        ]);
        return { users, products, categories };
    } catch (err) {
        console.error('Batch load failed:', err);
    }
}

Step 5: Extract reusable async functions

Break into small, testable functions:

async function readJSON(filePath) {
    const data = await readFile(filePath, 'utf8');
    return JSON.parse(data);
}

Prevention

  • Use async/await instead of nested callbacks for sequential operations.
  • Use util.promisify for callback-based Node.js APIs.
  • Use Promise.all for parallel asynchronous operations.
  • Break large async functions into smaller, named functions.
  • Use ESLint max-nested-callbacks rule to warn about excessive nesting.

Common Mistakes with callback hell

  1. Using foldl instead of foldl' causing stack overflow on large lists
  2. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  3. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable

These mistakes appear frequently in real-world NODE code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Is callback hell still relevant with modern JavaScript?

Yes. Many Node.js core modules and npm packages still use callbacks. Legacy codebases also contain callback patterns. Understanding how to refactor them into promises and async/await is essential for maintaining and modernizing existing projects.

Can I use async/await with any callback-based function?

Not directly. You must wrap the callback function in a Promise. Use util.promisify in Node.js for standard callback patterns (error-first callbacks). For other patterns, write a manual Promise wrapper. Once wrapped, you can use await on the returned promise.

What is the error-first callback convention?

Node.js uses the convention where the first argument to a callback is an error (or null if no error), and subsequent arguments contain the result data. util.promisify assumes this pattern. If a library uses a different convention, you must write a custom Promise wrapper.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro