# Callback Hell & Async Patterns

> What is callback hell in JavaScript? Why is it a problem, and how do Promises and async/await solve it?

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-callback-patterns
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

What is callback hell in JavaScript? Why is it a problem, and how do Promises and async/await solve it?

## Answer

Callback hell, also called the pyramid of doom, is what happens when each asynchronous step is nested inside the callback of the previous one, so the code drifts rightwards and error handling is repeated at every level. Promises fix it by returning an object representing the future result, which can be chained flatly with one `.catch()`. `async`/`await` goes further and lets you write the same Promise logic as straight-line code with `try/catch`.

### Why nested callbacks hurt

The indentation is the visible symptom, but the real problems are deeper:

- **Repeated error handling.** In Node's error-first style `(err, data) => {}`, every level needs `if (err) return ...`. Miss one and the error disappears silently.
- **Inversion of control.** You hand your continuation to someone else's code. A buggy library might call your callback twice, never, or synchronously sometimes and asynchronously other times. Promises guarantee a settled value exactly once and always resolve asynchronously.
- **Hard composition.** Running three requests in parallel and continuing when all are done requires manual counters. Timeouts and cancellation are worse.
- **Exceptions do not propagate.** A `throw` inside an async callback cannot be caught by a `try/catch` around the original call.

### How Promises flatten the code

A Promise is a placeholder for a value that is pending, then either fulfilled or rejected. `.then()` returns a **new** Promise, and if your handler returns a Promise, the chain waits for it. That is why a chain stays flat. Any rejection or thrown error skips ahead to the nearest `.catch()`, giving you one place for error handling. Combinators like `Promise.all`, `allSettled`, `race` and `any` handle parallel work that callbacks made painful.

### async/await on top of Promises

An `async` function always returns a Promise. Inside it, `await` pauses that function (not the thread) until the Promise settles, then resumes with the value or throws the rejection reason. You get normal `try/catch/finally`, normal loops and normal variables across steps, which is why it is the default style in 2026 codebases.

|  | Callbacks | Promise chain | async/await |
| --- | --- | --- | --- |
| Shape | Nested | Flat chain | Sequential lines |
| Errors | Checked at every level | One `.catch()` | `try/catch` |
| Parallel work | Manual counters | `Promise.all` | `await Promise.all` |
| Guarantees | None | Settles once, async | Same as Promises |

### Mistakes that bring the pain back

- **Accidental waterfalls.** `await a(); await b();` runs sequentially even when `b` does not need `a`. Start both and `await Promise.all([a(), b()])`.
- **Nesting `.then` inside `.then`.** Return the inner Promise instead.
- **Forgetting `await` or `return`.** The function moves on with a pending Promise and errors become unhandled rejections.
- **`await` inside `forEach`.** `forEach` ignores the returned Promises; use `for...of` for sequence or `Promise.all(items.map(...))` for parallel.
- **Converting old APIs.** Wrap callback APIs once with `new Promise` or Node's `util.promisify`, and prefer the built-in Promise versions such as `fs/promises`.

**Callbacks, promises and await on the event loop. The same work scheduled three ways. Rearrange the steps under Tweak and watch the order change.**

1. **A setTimeout callback is a task**: It waits for the task queue, after all microtasks.
2. **A promise callback is a microtask**: It runs as soon as the call stack empties.
3. **await resumes as a microtask**: async/await is promise scheduling written as straight-line code.
4. **Output**: async, sync, promise, async resumed, callback.

## Code examples

### From callback pyramid to Promise chain

```
// Callback hell: error checks repeated at every level
getUser(userId, (err, user) => {
  if (err) return handleError(err);
  getOrders(user.id, (err, orders) => {
    if (err) return handleError(err);
    getPaymentStatus(orders[0].id, (err, status) => {
      if (err) return handleError(err);
      console.log('Latest payment:', status);
    });
  });
});

// Same flow with Promise-returning versions: flat, one catch
getUser(userId)
  .then((user) => getOrders(user.id))          // returning a Promise keeps it flat
  .then((orders) => getPaymentStatus(orders[0].id))
  .then((status) => console.log('Latest payment:', status))
  .catch(handleError);                           // catches a failure from any step
```

Each then returns a new Promise, so returning the next async call flattens the chain. A single catch replaces three manual error checks.

### async/await with parallel work and promisify

```
import { promisify } from 'node:util';
import { readFile } from 'node:fs/promises';   // built-in Promise API
import legacyGeo from './legacy-geo.js';        // old callback-style library

const lookupPincode = promisify(legacyGeo.lookup); // (pin, cb) -> Promise

async function buildOrderSummary(userId) {
  try {
    const user = await getUser(userId);

    // Independent calls: start together, wait once (no waterfall)
    const [orders, address] = await Promise.all([
      getOrders(user.id),
      lookupPincode(user.pincode),
    ]);

    const template = await readFile('./summary.txt', 'utf8');
    return template.replace('{name}', user.name).replace('{count}', orders.length);
  } catch (err) {
    console.error('Summary failed:', err.message); // any step's rejection lands here
    throw err;
  }
}
```

await reads like synchronous code while Promise.all keeps independent requests parallel. promisify converts an error-first callback API into a Promise-returning one.

## Key points

- Callback hell is deep nesting of async callbacks with repeated error handling.
- The deeper issue is inversion of control: callbacks may be called twice, never, or synchronously.
- then always returns a new Promise; returning a Promise from a handler keeps chains flat.
- async functions always return a Promise; await pauses only that function, not the event loop.
- Use Promise.all for independent work and avoid await inside forEach.

## Common follow-up questions

- What does .then() return, and what happens if the handler throws?
- How would you convert a callback-based function to return a Promise?
- What is an unhandled rejection and how do you catch them globally?
- Why does await inside forEach not wait?
- How would you run 100 requests with at most 5 in flight at once?

## Interview tips

- Go beyond indentation: mentioning inversion of control and the trust guarantees of Promises impresses interviewers.
- Show the sequential vs parallel await difference; it is the most common practical follow-up.
- Be clear that async/await is syntax over Promises, not a different concurrency model.

## Concepts covered

Callback Hell, Inversion of Control, Promises, Async/Await, Error-first Callbacks

Previous: [Higher-Order Functions](https://www.internhack.in/learn/interview/javascript-interview/js-higher-order-functions) · Next: [Symbols & Well-Known Symbols](https://www.internhack.in/learn/interview/javascript-interview/js-symbols) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Proxy and Reflect API](https://www.internhack.in/learn/interview/javascript-interview/js-proxy-reflect)
- [WeakMap and WeakSet](https://www.internhack.in/learn/interview/javascript-interview/js-weakmap-weakset)
- [Generator Functions](https://www.internhack.in/learn/interview/javascript-interview/js-generators)
- [Optional Chaining and Nullish Coalescing](https://www.internhack.in/learn/interview/javascript-interview/js-optional-chaining-nullish)
- [Currying and Function Composition](https://www.internhack.in/learn/interview/javascript-interview/js-currying-composition)
- [Memoization](https://www.internhack.in/learn/interview/javascript-interview/js-memoization)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
