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: Pending → Fulfilled (resolve called) / Rejected (reject called).
- Settlement is permanent — no going back, no changing state again.
Promise guarantees
The fixes for Inversion of Control.
.thenis 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
.catchautomatically — no manual plumbing.
Chaining & error handling
Flat code, one catch.
.then()returns a NEW promise → chain top-to-bottom, no nesting.- Always
returnfrom .then — otherwise the next .then getsundefined. - One
.catchat the end catches errors from any step above (try/catch around the chain). .thenAFTER.catchstill runs — catch returns a resolved promise withundefined.
Comments
Comments are disabled in this environment. Set
PUBLIC_GISCUS_REPO,PUBLIC_GISCUS_REPO_ID, andPUBLIC_GISCUS_CATEGORY_IDto enable.