yellowyolkblue

fetch(), promises, and the event loop

The thing that finally made JavaScript click for me was realizing that await doesn't pause the program — it pauses your function and hands the single thread back to everyone else. The event loop keeps spinning. You just stepped out of line and said "call me when the network's done."

const res = await fetch("/api/voidlings/42");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const pet = await res.json();

Two gotchas bite everyone. First: fetch() only rejects on network failure, not on a 404 or 500 — so you must check res.ok yourself. Second: the response body is a one-shot stream. Call .json() twice and the second call throws because the stream's already drained.

Once the mental model is "one thread, a queue of callbacks, and promises that resolve later," every async bug gets a lot less spooky.