Promises & Async/Await
Some things don't finish instantly — loading data from a server, waiting on a timer, reading a file. Promises are how JavaScript represents "a value that isn't ready yet, but will be," and async/await is a way of writing code around that gap without it turning into a tangle of nested callbacks.
The problem: code doesn't wait
Run this and watch the order the messages print in:
Even though "Order ready" is written second in the code, it logs last. setTimeout schedules that message for later and JavaScript moves straight on to the next line without waiting — it never just pauses. Promises exist for exactly this kind of gap between starting something and it actually finishing.
Creating and using a Promise
A Promise wraps an operation that finishes later. Call resolve when it succeeds, and anything chained with .then runs once that happens:
If something goes wrong, call reject instead of resolve, and handle it with .catch:
async/await
async/await isn't a different tool from Promises — it's different syntax for working with the same ones. It lets asynchronous code read top to bottom, like ordinary synchronous code, instead of chaining .then calls:
await pauses just that function — not the whole page — until the promise settles, then hands back the resolved value directly. It only works inside a function marked async. To handle a rejection, wrap the await in a regular try/catch:
A simple fetch-like example
Real network requests, made with the browser's built-in fetch(), follow exactly this same pattern — they return a Promise that resolves once a response arrives. Here's a stand-in that behaves the same way, without needing an actual server:
Swap fakeFetch for the real fetch() and this code barely changes — that's the whole point of learning the pattern here.
fetch() calls and frameworks, builds directly on these fundamentals.