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 promiseinside anasyncfunction.
Key properties
- A promise settles once; later
resolve/rejectcalls 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
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}67delay(20, "data")8 .then((v) => v.toUpperCase())9 .then((v) => console.log("then:", v)) // then: DATA10 .catch((e) => console.log("caught:", e.message))11 .finally(() => console.log("finally: cleanup"));1213// Same thing with async/await14try {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: boom20}2122// Handlers are always async (microtasks), even for resolved promises23Promise.resolve("already done").then((v) => console.log("2.", v));24console.log("1. this logs first");2526// 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.