← 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
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 runsWait for many promises all, race, allSettled, any
Three requests 0 to 2 s
A 800 msok fail
B 400 msok fail
C 1400 msok fail
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 fulfillTopics
Next: How closures work
Open lesson