Search lands in PR-5.1 (Pagefind).

Explanation Intermediate

Chapter 14 Updated

Callbacks & Promises — From Problem to Solution

Why callbacks break and how promises fix both Callback Hell and Inversion of Control.

  • Full 14m
  • Revision 3m
  • Flow 2m

Callbacks — the good

Async programming's foundation.

  • JavaScript is synchronous and single-threaded — it does not wait for anything.
  • Callbacks let us hand JS a function to run later, when async work completes.
  • setTimeout, event listeners, fetch, I/O — all use callbacks under the hood.
  • Without callbacks, there is no async programming in JS.

Callback Hell

Pyramid of Doom.

  • Nested callbacks for sequential dependencies → code grows horizontally.
  • Each dependency adds indentation — 6 levels deep is unreadable, undebuggable.
  • Error handling requires try/catch at every nesting level.
  • Called “Pyramid of Doom” because of the triangular indentation shape.

Inversion of Control

The deeper, worse problem.

  • We hand our critical code (payment!) to someone else’s function — blindly trusting.
  • Callback might be called twice (double payment), never (order stuck), with wrong data, or at the wrong time.
  • Third-party code controls our business logic — zero guarantees.
  • This is why promises were invented — to give control BACK to us.

Promise — what & why

Placeholder for a future value.

  • Object representing the eventual completion or failure of an async operation.
  • Passing vs attaching: callbacks PASS our function (lose control); promises let us ATTACH our function to a returned promise (keep control).
  • Three states: PendingFulfilled (resolve called) / Rejected (reject called).
  • Settlement is permanent — no going back, no changing state again.

Promise guarantees

The fixes for Inversion of Control.

  • .then is called exactly once — no double-firing.
  • Result is immutable once settled — nobody can tamper with the data.
  • Callback is guaranteed to run when data is ready.
  • Errors propagate to .catch automatically — no manual plumbing.

Chaining & error handling

Flat code, one catch.

  • .then() returns a NEW promise → chain top-to-bottom, no nesting.
  • Always return from .then — otherwise the next .then gets undefined.
  • One .catch at the end catches errors from any step above (try/catch around the chain).
  • .then AFTER .catch still runs — catch returns a resolved promise with undefined.

Comments

Comments are disabled in this environment. Set PUBLIC_GISCUS_REPO, PUBLIC_GISCUS_REPO_ID, and PUBLIC_GISCUS_CATEGORY_ID to enable.