What is a Promise?

A Promise is an object representing a value that will be available later: the eventual success or failure of an asynchronous operation; you attach handlers with .then, .catch and .finally, or wait for it with await.

Why promises exist

They replaced deeply nested callbacks with a chainable, composable model where errors flow to a single handler, and they are the foundation of async/await.

Creating one

new Promise((resolve, reject) => { ... }) runs the executor immediately. Call resolve(value) on success or reject(error) on failure. In practice you mostly consume promises returned by APIs like fetch rather than creating them. Shortcuts: Promise.resolve(value), Promise.reject(error), and Promise.withResolvers() (ES2024), which returns { promise, resolve, reject } for cases where you resolve from outside.

Consuming

  • .then(onSuccess) returns a new promise, which enables chaining.
  • .catch(onError) handles any rejection earlier in the chain.
  • .finally(fn) runs either way, for cleanup like hiding a spinner.
  • await promise inside an async function.

Key properties

  • A promise settles once; later resolve/reject calls are ignored.
  • Handlers always run asynchronously, as microtasks, even if the promise is already resolved.
  • Unhandled rejections produce warnings (and can crash Node.js), so always handle errors.

Combinators

Promise.all, allSettled, race and any run several promises together.

Code example

js
1function delay(ms, value, shouldFail = false) {
2 return new Promise((resolve, reject) => {
3 setTimeout(() => (shouldFail ? reject(new Error(`Failed: ${value}`)) : resolve(value)), ms);
4 });
5}
6
7delay(20, "data")
8 .then((v) => v.toUpperCase())
9 .then((v) => console.log("then:", v)) // then: DATA
10 .catch((e) => console.log("caught:", e.message))
11 .finally(() => console.log("finally: cleanup"));
12
13// Same thing with async/await
14try {
15 const v = await delay(10, "with await");
16 console.log(v);
17 await delay(10, "boom", true);
18} catch (e) {
19 console.log("caught:", e.message); // caught: Failed: boom
20}
21
22// Handlers are always async (microtasks), even for resolved promises
23Promise.resolve("already done").then((v) => console.log("2.", v));
24console.log("1. this logs first");
25
26// Resolve from outside with Promise.withResolvers (ES2024)
27const { promise, resolve } = Promise.withResolvers();
28setTimeout(() => resolve("resolved externally"), 10);
29console.log(await promise);

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app