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:

Try it yourself
Console output

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:

Try it yourself
Console output

If something goes wrong, call reject instead of resolve, and handle it with .catch:

Try it yourself
Console output

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:

Try it yourself
Console output

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:

Try it yourself
Console output

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:

Try it yourself
Console output

Swap fakeFetch for the real fetch() and this code barely changes — that's the whole point of learning the pattern here.

Course complete: that covers the full JavaScript course — variables, data types, operators, conditionals, loops, functions, the DOM, arrays and objects, events, modern syntax like template literals and destructuring, JSON, and handling errors and asynchronous code. Together with HTML and CSS, you now have what it takes to build real, interactive pages — and everything from here, including real fetch() calls and frameworks, builds directly on these fundamentals.