JavaScript Promises Explained: States, then, catch, finally and Creating Promises
A clear guide to promises: what a promise represents, pending, fulfilled, rejected, settled and resolved, consuming results with then, catch and finally, creating promises with new Promise, resolve and reject, Promise.withResolvers, Promise.try, promisifying callback APIs, and common mistakes.
kvi5hnuCode Sprout team member6 min readOn this page
A promise is an object that represents the future result of an asynchronous operation: a value that isn't available yet, or an error that hasn't happened yet. Instead of passing a callback into a function (article 94), the function returns a promise, and you attach handlers to it. Almost every modern async API returns one: fetch, response.json(), Node's fs/promises, database drivers, and every async function.
fetch("/api/profile") // returns a promise immediately
.then((response) => response.json()) // runs when the response arrives
.then((profile) => showProfile(profile))
.catch((error) => showError(error)); // runs if anything above failed
Promise states

| Term | Meaning |
|---|---|
| pending | the operation hasn't finished; no value yet |
| fulfilled | it succeeded and has a value |
| rejected | it failed and has a reason (usually an Error) |
| settled | fulfilled or rejected: the outcome is final and never changes |
| resolved | its fate is decided: either settled, or locked onto another promise that will decide it |
The last row is subtle: resolving a promise with another promise doesn't fulfill it; it makes the first promise follow the second. Article 96 shows why this matters for chaining.
const done = Promise.resolve(42);
const waiting = new Promise(() => {}); // never settles
const failed = Promise.reject("network down");
failed.catch(() => {}); // handled, so no warning
console.log(done, waiting, failed);
Promise { 42 } Promise { <pending> } Promise { <rejected> 'network down' }
There's no way to read a promise's value synchronously. Node's console shows the state for debugging, but code must use then or await.
Consuming promises: then, catch, finally
function loadScore(player) {
return player === "ana" ? Promise.resolve(87) : Promise.reject(new Error(`Unknown player: ${player}`));
}
loadScore("ana")
.then((score) => console.log("score:", score))
.catch((err) => console.log("error:", err.message))
.finally(() => console.log("hide spinner"));
loadScore("zed")
.then((score) => console.log("score:", score))
.catch((err) => console.log("error:", err.message))
.finally(() => console.log("hide spinner"));
score: 87
error: Unknown player: zed
hide spinner
hide spinner
then(onFulfilled)runs with the value when the promise fulfills.catch(onRejected)runs with the reason when it rejects. It's shorthand forthen(undefined, onRejected).finally(onFinally)runs either way, without receiving the value or reason. Use it for cleanup like hiding a loading spinner or closing a connection.- Each method returns a new promise, which is what makes chaining possible (article 96).
Notice the interleaving in the output: both chains advance one step per microtask round, so their lines alternate rather than each chain finishing first.
Handlers are always asynchronous
Even if the promise is already settled, handlers run later, as microtasks (article 94), never immediately:
const ready = Promise.resolve("value");
ready.then((v) => console.log("2. handler got", v));
console.log("1. after calling then");
1. after calling then
2. handler got value
This guarantee removes a whole class of bugs that callback APIs had: you always know that code after .then(...) runs before the handler.
Many handlers, any time
A promise can have any number of handlers, and handlers added after it settled still run with the same value. The operation itself runs only once:
const config = new Promise((resolve) => setTimeout(resolve, 10, { theme: "dark" }));
config.then((c) => console.log("header uses", c.theme));
config.then((c) => console.log("sidebar uses", c.theme));
setTimeout(() => config.then((c) => console.log("late widget uses", c.theme)), 50);
header uses dark
sidebar uses dark
late widget uses dark
That makes promises a natural way to cache async results: store the promise, and everyone who asks gets the same eventual value.
Creating promises: new Promise
Most of the time you consume promises from APIs. When you need to wrap a callback-based API, use the Promise constructor. It takes an executor function that receives two functions, resolve and reject:
function delay(ms, value) {
return new Promise((resolve) => {
setTimeout(() => resolve(value), ms);
});
}
console.log("start");
delay(20, "twenty ms later").then((msg) => console.log(msg));
start
twenty ms later
Rules of the executor:
const p = new Promise((resolve, reject) => {
console.log("1. the executor runs immediately, synchronously");
resolve("first");
resolve("second"); // ignored: already resolved
reject(new Error("also ignored")); // ignored
});
console.log("2. constructor returned");
p.then((v) => console.log("3. value:", v));
new Promise(() => {
throw new Error("thrown inside the executor");
}).catch((err) => console.log("4. rejected with:", err.message));
1. the executor runs immediately, synchronously
2. constructor returned
3. value: first
4. rejected with: thrown inside the executor
- The executor runs synchronously inside the constructor. Only the handlers are async.
- Only the first call to
resolveorrejectcounts; later calls are silently ignored. - A
throwinside the executor rejects the promise (but a throw inside a later callback, like asetTimeoutcallback inside the executor, does not; callrejectthere). - Reject with
Errorobjects, not strings, so you get stack traces andinstanceofchecks. - Calling
resolvedoesn't stop the executor;returnafter it if more code follows.
Promise.resolve and Promise.reject
Promise.resolve(42); // an already-fulfilled promise
Promise.reject(new Error("no")); // an already-rejected promise
Promise.resolve(existingPromise); // returns the same promise object
Promise.resolve(thenable); // adopts any object with a then method
Promise.resolve is handy for functions that must always return a promise, for example returning a cached value: if (cache.has(key)) return Promise.resolve(cache.get(key));.
Promise.withResolvers (ES2024)
Sometimes resolve and reject need to be called from outside the executor, such as from an event handler set up elsewhere. Promise.withResolvers() returns all three pieces:
const { promise, resolve, reject } = Promise.withResolvers();
promise.then((answer) => console.log("user chose:", answer));
// later, e.g. inside a dialog's button handlers:
setTimeout(() => resolve("confirm"), 10);
user chose: confirm
It replaces the old pattern of declaring let resolve; and assigning it inside new Promise(...).
Promise.try (ES2025)
Promise.try(fn) calls fn and always gives back a promise: a synchronous return value fulfills it, a synchronous throw rejects it, and a returned promise is followed. It's useful when a function might fail before it reaches any async code:
Promise.try(() => JSON.parse("{not json"))
.then((data) => console.log("parsed", data))
.catch((err) => console.log("caught", err.name));
caught SyntaxError
Without it, Promise.resolve(JSON.parse(...)) would throw synchronously before any promise exists.
Promisifying callback APIs
To convert an error-first callback function (article 94) into a promise-returning one, wrap it:
function legacyRead(name, callback) {
setTimeout(() => {
if (name) callback(null, `contents of ${name}`);
else callback(new Error("missing file name"));
}, 5);
}
function promisify(fn) {
return (...args) =>
new Promise((resolve, reject) => {
fn(...args, (err, result) => (err ? reject(err) : resolve(result)));
});
}
const read = promisify(legacyRead);
read("notes.txt").then((text) => console.log(text));
read("").catch((err) => console.log("rejected:", err.message));
contents of notes.txt
rejected: missing file name
Node ships this as util.promisify, and most core modules already have promise versions: import { readFile } from "node:fs/promises".
Promises vs callbacks vs events
Promises represent one result. They're perfect for "do this, then tell me how it went" operations: requests, file reads, timers, dialogs. For things that happen repeatedly, like clicks, WebSocket messages or setInterval ticks, use event listeners or async iterators (article 99).
Common mistakes
- Expecting a value instead of a promise:
const data = fetch(url); data.namedoesn't work; use.thenorawait. - Forgetting
returninside a.thencallback, which breaks the chain (article 96). - No
catch: rejected promises without a handler trigger "unhandled rejection" warnings in browsers and crash Node processes by default. - Wrapping promises in
new Promiseunnecessarily (the "explicit construction anti-pattern"): if a function already returns a promise, return it or chain on it.
Common questions
Does creating a promise start the operation?
The executor runs immediately, so the work starts when the promise is created, not when you call then. Promises are "eager"; to delay work, wrap it in a function that returns a promise.
Can I cancel a promise?
Not directly. A promise is a result, not the operation itself. Cancel the underlying operation instead, typically with an AbortController signal (for fetch and many other APIs).
What's the difference between resolved and fulfilled?
Fulfilled means it has a value. Resolved means its outcome is determined: it may be fulfilled or rejected already, or it may be locked onto another promise that is still pending.
Why does my .then callback receive undefined?
The previous step didn't return anything. Return the value (or promise) from each then callback that the next step needs.
Summary
- A promise represents the eventual result of an async operation: pending, then fulfilled with a value or rejected with a reason, and settled forever after.
then,catchandfinallyregister handlers, always run asynchronously as microtasks, and each returns a new promise.- A promise can have many handlers, including late ones; the operation runs once.
new Promise((resolve, reject) => ...)wraps callback APIs; the executor runs synchronously, only the first settle call counts, and a throw rejects.Promise.resolve,Promise.reject,Promise.withResolversandPromise.trycover the other ways to create promises;util.promisifyconverts Node-style callbacks.
Practice Questions
What's the output order?
console.log("A");
new Promise((r) => { console.log("B"); r(); }).then(() => console.log("C"));
console.log("D");
Answer
A, B, D, C. The executor runs synchronously; the then handler runs as a microtask after the script.
Write loadImage(src) that returns a promise for a browser Image, rejecting on error.
Answer
function loadImage(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error(`Failed to load ${src}`));
img.src = src;
});
}
What does this log?
const p = new Promise((res, rej) => { rej(new Error("x")); res(1); });
p.then((v) => console.log("value", v), (e) => console.log("error", e.message));
Answer
error x. The first settle call wins; res(1) is ignored.
Why is this code inside an executor not turned into a rejection?
setTimeout(() => { throw new Error("late"); })
Answer
The throw happens later, inside the timer callback, after the executor has returned. Only synchronous throws in the executor are caught. Call reject(new Error("late")) inside the timer callback instead.
Previous: Asynchronous JavaScript: Callbacks, the Event Loop, Tasks and Microtasks

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.