Belajar
← All lessons

How promises work

A promise, from pending to settled

Your code
Promise
Server

then.js

const p = fetch("/api/user");console.log(p); // Promise {<pending>} p.then((res) => res.json())  .then((user) => show(user))  .catch((err) => showError(err));

await.js

// the same request, written with awaitasync function load() {  try {    const res = await fetch("/api/user");    const user = await res.json();    show(user);  } catch (err) {    showError(err);  }}

Build a chain and see where each value goes

startresolve(1)rejectfirst .thenreturnthrowsecond .thenreturnthrow
What ran, in order

    chain.js

    const start = Promise.resolve(1);// or: Promise.reject(new Error("start")) start  .then((x) => {    if (failA) throw new Error("A");    return x + 1;  })  .catch((err) => 0) // recovers  .then((x) => {    if (failB) throw new Error("B");    return x * 10;  })  .finally(() => cleanUp()); // always runs

    Wait for many promises all, race, allSettled, any

    Combine them withallraceallSettledany
    Three requests 0 to 2 s
    A
    800 msokfail
    B
    400 msokfail
    C
    1400 msokfail
    The combined promise

    combine.js

    const reqs = [get("A"), get("B"), get("C")]; await Promise.all(reqs);        // all fulfill, or the first rejectionawait Promise.race(reqs);       // the first to settleawait Promise.allSettled(reqs); // waits for all, never rejectsawait Promise.any(reqs);        // the first to fulfill

    Topics

    Next: How closures work

    Open lesson