Async
Promises: Promise
A value that will be ready later — or an error.
Why it exists
The network, disk and timers are slow, and JavaScript in the browser runs on one thread. If it waited for the server's response, the page would freeze. Instead, a slow operation immediately returns a promise — a "receipt" you can redeem for the result when it arrives. Meanwhile the program keeps running: the interface responds to clicks, animations play.
Where it's used
- Server requests:
fetch(url)returns a promise of the response. - Any library that touches the network or disk: databases, files, payments.
- Delays and waiting for events:
new Promise((r) => setTimeout(r, 1000)). - async functions: they always return a promise.
Syntax
const p = new Promise((resolve, reject) => {
// later: resolve(value) or reject(error)
});
const value = await p;Examples
const ready = Promise.resolve(42);
ready.then((value) => console.log(value)); // 42const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await wait(10);
"10 ms passed"; // → "10 ms passed"const failing = Promise.reject(new Error("No network"));
let message;
try {
await failing;
} catch (error) {
message = error.message;
}
message; // → "No network"await turns a rejection into an errorconst doubled = await Promise.resolve(21).then((n) => n * 2);
doubled; // → 42then returns a new promiseResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
A promise has three states: pending, fulfilled with a value, and rejected with an error. It moves from pending to one of the two final states exactly once and never changes again.
new Promise((resolve, reject) => { … }) creates a promise by hand: the executor function runs immediately and later calls resolve(value) or reject(error).
There are two ways to get the result. await p inside an async function pauses it until the promise finishes and gives the value (or throws the error). p.then(onFulfilled, onRejected) registers callbacks and returns a new promise — so calls can be chained; .catch(fn) is the same as .then(undefined, fn); .finally(fn) runs either way.
Promise callbacks are always called asynchronously — after the current synchronous code finishes, even if the promise is already settled.
Traps
How it differs from…
async/awaitasync/awaitis convenient syntax on top of promises: the same mechanism, but the code reads top to bottom like ordinary code.Promise.all,race,allSettled,anyPromise.all,
race,allSettledandanycombine several promises into one.
When to pick something else
Don't wrap synchronous code in a promise "for the future" — it only complicates it. And you rarely need to write new Promise by hand: most APIs (fetch, libraries) already return promises. They're mostly created by hand to wrap old callback-based APIs like setTimeout.
Practice
Lessons where this appears
- The pizza is on its wayTale · Chapter 16 · Async
- Why doesn't setTimeout(…, 0) fire at once?Why? · Chapter 16 · Async
- Byte's pizzeriaWorkshop · Chapter 16 · Async
- All the prices at onceLab · Chapter 16 · Async
- A call to the warehouseTale · Chapter 21 · The network: fetch and HTTP
- His Majesty the ReleaseBoss · Chapter 29 · Final project: a weather app