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

Promise lifecycle — from call to settled

flowchart TD
    A["<b>i · createOrder(cart)</b><br/>called synchronously"]
      --> B["<b>ii · Promise returned</b><br/>state: pending<br/>result: undefined"]
    B --> C["<b>iii · JS continues</b><br/>engine does not wait"]
    C --> D["<b>iv · async work runs</b><br/>setTimeout / fetch / I/O"]
    D --> E{"<b>v · settle</b>"}
    E -- success --> F["<b>vi · Fulfilled</b><br/>result = value"]
    E -- failure --> G["<b>vii · Rejected</b><br/>result = error"]
    F --> T[".then(callback) fires once"]
    G --> K[".catch(handler) fires once"]
 
    classDef head   fill:#f5efe1,stroke:#6a8a4f,stroke-width:2px,color:#1a1915;
    classDef hub    fill:#fdecd3,stroke:#c2410c,stroke-width:2px,color:#1a1915;
    classDef ok     fill:#e7efd9,stroke:#587640,stroke-width:2px,color:#1a1915;
    classDef err    fill:#f5e1e1,stroke:#8a4f4f,stroke-width:2px,color:#1a1915;
    class A head
    class B,C,D,E hub
    class F,T ok
    class G,K err
  • createOrder(cart)

    The async function is called. It does not block — it returns immediately.

  • Promise returned

    A placeholder object in the pending state. Result is undefined. We can attach .then/.catch to it right now.

  • JS continues

    The engine continues executing other code. Call stack is never blocked while the async work runs.

  • async work runs

    The actual async operation (timer, network, I/O) runs outside the call stack via Web APIs.

  • Settle

    When the async work completes, the executor calls resolve(value) or reject(error). Settlement is permanent.

  • Fulfilled

    State flips to fulfilled, result becomes the value. Every attached .then fires exactly once.

  • Rejected

    State flips to rejected, result becomes the error. Every attached .catch fires exactly once.

Comments

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