Promises in JavaScript: The Complete Guide
A complete guide to JavaScript promises on Node.js 24: states, chaining, errors, combinators, thenables, unhandled rejections, patterns and common mistakes.

Promises are the part of JavaScript that everything asynchronous is built on. fetch returns one. Every async function returns one. await consumes one. Even code that never mentions the word is using them, because the language and its libraries deliver the results of slow operations as promises. And yet promises are routinely used without being understood, which is why the same handful of bugs appear in nearly every code base: a handler that forgot to return, a rejection nobody handled, a chain that fires in the wrong order, a new Promise wrapped around a promise that already existed. This guide gives you the whole picture on Node.js 24 and in current browsers. It starts with what a promise is and the three rules that govern it, then covers creating, consuming and chaining promises, handling errors, the combinators, the newer helpers, unhandled rejections, thenables, patterns you will write again and again, testing, debugging and the mistakes to avoid. Every example prints the output it produces, so you can check your reading against it.
You can read the guide straight through or jump to a section. Each one stands alone, and the links point to deeper posts on the individual topics.
What a promise is
A promise is an object that represents the eventual result of an operation. When you start something slow, such as a network request, you do not get its result, because it does not exist yet. You get a promise, an object you can hold, pass around and attach instructions to, which will receive the result when it arrives. A promise is in exactly one of three states. Pending means the operation has not finished. Fulfilled means it finished with a value. Rejected means it failed with a reason, which is nearly always an Error. Fulfilled and rejected together are called settled, and a settled promise never changes again.
const pending = new Promise(() => {});
const fulfilled = Promise.resolve(42);
const rejected = Promise.reject(new Error("failed"));
rejected.catch(() => {});
console.log(pending);
console.log(fulfilled);
console.log(rejected.constructor.name);Promise { <pending> }
Promise { 42 }
PromiseThe first promise never settles, because nothing ever calls its resolve function. The second is fulfilled with 42. The third is rejected, and the catch marks the rejection as handled so the runtime does not report it. The state is not directly readable from code. There is no promise.state property, and you observe a promise only by attaching handlers, which is a deliberate design choice: the answer to "is it done?" is always "tell me when it is".
Three rules govern everything else in this guide.
Rule 1: a promise settles at most once. The first call to resolve or reject decides the outcome, and every later call is ignored. A consumer can therefore trust that it will see exactly one result.
Rule 2: handlers always run asynchronously. A function attached with then runs as a microtask, after the current synchronous code finishes, even if the promise settled long ago. This guarantees the same ordering whether the result was ready or not, which callbacks cannot promise.
**Rule 3: then returns a new promise.** What the new promise does depends on what your handler returns or throws, and that is what makes chaining work.
The post on promise states, settling and chaining walks through each of the three, and the chaining rule has its own post as well, how then returns a new promise.
Creating promises
The constructor takes an executor function, which receives resolve and reject. The executor runs immediately and synchronously when you call new Promise, which means creating a promise starts the work. Promises are not lazy.
console.log("before");
const promise = new Promise((resolve) => {
console.log("executor runs now");
resolve("done");
});
console.log("after");
promise.then((value) => console.log("then:", value));before
executor runs now
after
then: doneThe executor's body ran between before and after. Only the then handler waited. If the executor throws, the promise is rejected with the thrown value, so synchronous errors inside it are not lost.
const failed = new Promise(() => {
throw new Error("thrown in the executor");
});
failed.catch((error) => console.log("caught:", error.message));caught: thrown in the executorThe most common reason to write new Promise is to wrap an API that uses a callback. Do it once, in one place, and let the rest of the program use the promise.
import { readFile } from "node:fs";
function readText(path) {
return new Promise((resolve, reject) => {
readFile(path, "utf8", (error, text) => {
if (error) reject(error);
else resolve(text);
});
});
}
console.log((await readText("package.json")).length > 0);
try {
await readText("/does/not/exist");
} catch (error) {
console.log(error.code);
}true
ENOENTFor error-first callbacks, util.promisify does exactly this, and the modules node:fs/promises, node:timers/promises, node:dns/promises and others already ship promise versions of their functions. Reach for those before writing a wrapper. The post on error-first callbacks describes the convention being wrapped.
Two static methods create settled promises without an executor. Promise.resolve(value) returns a promise fulfilled with the value, with two special cases: if the value is already a native promise, you get the same promise back, and if it is a thenable, the result follows it. Promise.reject(reason) returns a rejected promise, with no unwrapping. The asymmetry is explained in the post on resolve and reject.
const original = Promise.resolve("x");
console.log(Promise.resolve(original) === original);
const inner = Promise.resolve("inner");
Promise.reject(inner).catch((reason) => console.log(reason === inner));true
truePromise.resolve unwraps and Promise.reject does not, so rejecting with a promise stores the promise itself as the reason. By convention, always reject with an Error object, which carries a stack trace.
When the code that creates a promise is not the code that settles it, such as a reply that arrives as a separate event, the executor pattern becomes awkward, and Promise.withResolvers() returns the promise together with its resolve and reject functions in one object. It arrived in ES2024 and is available in Node.js 22 and later.
const { promise, resolve } = Promise.withResolvers();
setTimeout(() => resolve("settled from outside"), 10);
console.log(await promise);settled from outsideThe details, with uses such as matching replies to requests and async queues, are in the post on Promise.withResolvers.
Consuming promises: then, catch and finally
You attach handlers with three methods. then(onFulfilled, onRejected) registers up to two functions, catch(onRejected) is shorthand for then(undefined, onRejected), and finally(onFinally) registers a function that runs either way, with no arguments, and passes the original outcome through unchanged.
Promise.resolve("data")
.then((value) => console.log("fulfilled:", value))
.finally(() => console.log("finally runs"));
Promise.reject(new Error("failed"))
.catch((error) => console.log("rejected:", error.message))
.finally(() => console.log("finally runs again"));
console.log("handlers attached");handlers attached
fulfilled: data
rejected: failed
finally runs
finally runs againBoth promises were already settled, and the handlers still ran after the synchronous line, as rule 2 says. Notice also that you can attach as many handlers as you like to one promise, and each receives the same value, in the order you attached them. A promise is a broadcast of one result, not a queue that a consumer empties.
finally is for cleanup, such as hiding a spinner or releasing a lock. It cannot change the value, and its return value is ignored, with one exception: if the finally function throws or returns a rejected promise, the chain becomes rejected with that reason.
Chaining
Because then returns a new promise, you can chain calls, and each step receives the result of the previous one. The new promise's outcome follows three rules.
If the handler returns a plain value, the new promise fulfills with it. If it returns a promise, or any thenable, the new promise waits for that promise and takes on its outcome. If it throws, the new promise rejects with the thrown value. A step that has no handler for the current outcome passes the outcome through unchanged, which is how a rejection travels down a chain until it meets a catch.
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const result = await Promise.resolve(3)
.then((n) => n * 2)
.then((n) => delay(10, n + 1))
.then((n) => `result: ${n}`);
console.log(result);result: 7The second step returned a promise, and the chain waited ten milliseconds for it before passing 7 to the third step. This is the feature that turns a pyramid of callbacks into a flat sequence.
The most common mistake in a chain is forgetting to return.
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
await delay(5, "a")
.then((value) => {
delay(20, "b"); // missing return: the chain does not wait
})
.then((value) => console.log("next step got:", value));
console.log("chain finished");
await delay(40);next step got: undefined
chain finishedThe inner promise was created and abandoned. The chain moved on immediately with undefined, and if the abandoned promise had rejected, nothing would have handled it. An arrow function with a block body returns nothing, while one with an expression body returns its value, which is why (x) => fn(x) and (x) => { fn(x) } behave differently.
The second chaining mistake is nesting.
const getUser = () => Promise.resolve({ id: 1 });
const getPosts = (id) => Promise.resolve([`post of ${id}`]);
// nested: the error path is disconnected from the outer chain
getUser().then((user) => {
getPosts(user.id).then((posts) => console.log("nested:", posts));
});
// flat: return the inner promise and keep going
getUser()
.then((user) => getPosts(user.id))
.then((posts) => console.log("flat:", posts));nested: [ 'post of 1' ]
flat: [ 'post of 1' ]Both print the same result, but a rejection inside the nested version never reaches a catch on the outer chain, because the outer handler returned nothing. Return the inner promise, and keep the chain at one level.
A chain is also not the same as several handlers on one promise. Calling then repeatedly on the same promise creates branches that each receive the original value. Calling then on the result of then creates a chain, where each step receives the previous step's return value. Mixing them up is a common source of "why is my value the old one" bugs.
Handling errors
Rejections travel down a chain, skipping every then that has no rejection handler, until a handler takes them. A catch at the end of a chain handles a failure from any step above it, including a throw inside a then handler.
Promise.resolve("start")
.then((value) => {
console.log("step 1:", value);
throw new Error("step 1 failed");
})
.then(() => console.log("step 2 never runs"))
.catch((error) => {
console.log("caught:", error.message);
return "recovered";
})
.then((value) => console.log("step 3:", value));step 1: start
caught: step 1 failed
step 3: recoveredA catch returns a promise too. If its handler returns normally, the chain is fulfilled again and continues. If you want a failure to keep failing after you log it, rethrow inside the catch. Swallowing an error by accident, with a catch that logs and returns nothing, is the most common way a failure becomes invisible.
Promise.reject(new Error("db error"))
.catch((error) => {
console.log("logging:", error.message);
throw error;
})
.catch((error) => console.log("still failing:", error.message));logging: db error
still failing: db errorAlways reject with Error objects, and wrap a caught error with a cause when you rethrow a more specific one: throw new Error("could not load user", { cause }). A bare new error discards the original stack, which is often the only one that names the failing line.
There is a subtle difference between then(a, b) and then(a).catch(b). In the first form, b handles failures of the earlier promise only, and not errors thrown by a. In the second, the catch also handles errors thrown by a. Prefer the second form unless you specifically want the first.
Unhandled rejections
A rejected promise with no handler attached when the runtime checks is an unhandled rejection. The check happens after the microtask queue drains, so a handler attached in the same turn counts, and one attached in a later task is too late. Runtimes treat it as a bug.
Node.js 15 and later throws it as an uncaught exception by default, which ends the process with exit code 1, unless an unhandledRejection listener on process exists. Browsers log an error to the console and fire an unhandledrejection event on window. Deno behaves like browsers but exits, and Bun follows Node.js.
process.on("unhandledRejection", (reason) => {
console.log("unhandled:", reason.message);
});
Promise.reject(new Error("nobody is listening"));unhandled: nobody is listeningA listener like this is the place for your own logging and reporting at the edge of a program, and not a way to make the problem go away. The causes are nearly always one of a few patterns: a missing await on a call whose promise rejects, an async callback passed to forEach, an async event handler whose rejection nobody reads, or a branch of a chain that never got a catch. The post on unhandled rejections covers the policies, the events in each runtime and how to find the source.
Combining promises
Four static methods combine several promises into one. They differ in what they do when an input rejects and when they settle.
| Method | Fulfills when | Rejects when | Result |
|---|---|---|---|
Promise.all | All fulfill | Any rejects (first one wins) | Array of values in input order |
Promise.allSettled | All settle | Never | Array of { status, value or reason } |
Promise.race | First settles with success | First settles with failure | The first outcome |
Promise.any | First fulfills | All reject (AggregateError) | The first value |
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const failAfter = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
console.log(await Promise.all([delay(20, "a"), delay(10, "b")]));
const settled = await Promise.allSettled([delay(10, "ok"), failAfter(5, "bad")]);
console.log(settled.map((r) => r.status));
console.log(await Promise.race([delay(30, "slow"), delay(10, "fast")]));
console.log(await Promise.any([failAfter(5, "x"), delay(15, "winner")]));[ 'a', 'b' ]
[ 'fulfilled', 'rejected' ]
fast
winnerChoosing between them means deciding what a failure means. Use all when every result is needed and one failure makes the others worthless. Use allSettled when each result stands alone, such as the widgets on a dashboard or the records in a batch, and you want to report failures without losing successes. Use race when the first outcome decides, most often for a timeout against real work. Use any for redundant sources such as mirrors, where only one success is needed. Each has a full post: all, allSettled, race and any.
Three facts apply to all four. They accept any iterable, and plain values count as already fulfilled. The promises are already running when you call them, so none of the combinators starts work or limits how much is in flight. And none cancels the others when one settles, so the work behind a losing promise continues. If a loop of five thousand items becomes five thousand promises, all five thousand requests are active. A bounded pool, shown in the patterns section, is the cure.
Awaiting a loop of independent work one item at a time is also a common waste. The sequential version takes the sum of the waits, and the combined version takes the longest one.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
let start = Date.now();
for (const ms of [20, 20, 20]) await wait(ms);
const sequential = Date.now() - start;
start = Date.now();
await Promise.all([20, 20, 20].map(wait));
const together = Date.now() - start;
console.log("sequential at least 55 ms:", sequential >= 55);
console.log("together under 50 ms:", together < 50);sequential at least 55 ms: true
together under 50 ms: trueStarting from sync or async code
Sometimes you have a function that might be synchronous and might return a promise, and you want one error path for both. Writing new Promise((resolve) => resolve(fn())) works but is noisy, and Promise.resolve().then(fn) delays the call by a microtask. Promise.try(fn, ...args) calls the function immediately and returns a promise: a return value fulfills it, a returned promise is followed and a throw rejects it. It is part of ES2025 and available in Node.js 24.
function parseConfig(text) {
return Promise.try(() => JSON.parse(text));
}
console.log(await parseConfig('{"port": 8080}'));
await parseConfig("{broken").catch((error) => console.log(error.name));{ port: 8080 }
SyntaxErrorA function declared async already behaves this way, so Promise.try is for functions you did not write or cannot change, and for places where running the function synchronously, in order with the surrounding code, matters. The post on Promise.try covers the comparison with Promise.resolve().then.
Thenables and interoperability
A thenable is any object with a then method. Native promises are thenables, and so are the promise-like objects of older libraries. Promise.resolve, await, the combinators and the return value of a then handler all recognize thenables and follow them by calling their then with a pair of callbacks. This is how different promise implementations cooperate, and it is why query builders can return objects that run when awaited.
const thenable = {
then(resolve) {
resolve("from a thenable");
},
};
console.log(await thenable);
console.log(await Promise.resolve(thenable));from a thenable
from a thenableThe convenience has costs. Adopting a thenable takes an extra microtask, so awaiting one is slower than awaiting a native promise. A thenable's work runs every time it is awaited, since nothing caches the result. And an object that has a method named then for some unrelated reason will be adopted as a promise, and await on it hangs if the method never calls back. Avoid the name then on ordinary objects, and convert foreign promise-likes with Promise.resolve at the boundary of your code. The post on thenables covers the edge cases, including a then that calls back twice or throws.
Promises, microtasks and timing
Promise handlers run as microtasks, and microtasks run before the next task, so a promise callback always beats a setTimeout callback, even one with a zero delay. The ordering has consequences you can use and consequences that bite.
setTimeout(() => console.log("timer"), 0);
Promise.resolve()
.then(() => console.log("promise 1"))
.then(() => console.log("promise 2"));
console.log("sync");sync
promise 1
promise 2
timerA long chain of promises runs entirely before any timer, any input event or, in a browser, any rendering. A chain that never ends starves them all. The event loop guide, the event loop explained, covers the model, and the post on microtasks and macrotasks covers the starvation case.
A related point is that await is built on promises. An async function returns a promise, and await promise is the same as attaching the rest of the function as a then handler. Everything in this guide applies to async/await unchanged, which is the subject of its own guide, async/await in JavaScript.
Patterns you will write again and again
Promises are a small API, and a short list of helpers covers most real needs.
A delay. Wrap setTimeout once.
const sleep = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
console.log(await sleep(10, "slept"));sleptIn Node.js, setTimeout from node:timers/promises is the built-in version, and it accepts an AbortSignal.
A timeout. Race the work against a timer, and clear the timer afterwards. The modern form passes an AbortSignal.timeout to the work itself, which also stops it.
function withTimeout(promise, ms) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`timed out after ${ms} ms`)), ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
try {
await withTimeout(sleep(100), 10);
} catch (error) {
console.log(error.message);
}timed out after 10 msThe finally clears the timer so that a successful result does not leave a pending timer holding the process open. Note that this does not cancel the slow work, only the waiting. For work that can be cancelled, use a signal, as in the cancellation guide.
Retry with backoff.
async function retry(operation, attempts = 3, baseMs = 10) {
let lastError;
for (let attempt = 1; attempt <= attempts; attempt++) {
try {
return await operation(attempt);
} catch (error) {
lastError = error;
if (attempt < attempts) await sleep(baseMs * 2 ** (attempt - 1));
}
}
throw new Error(`failed after ${attempts} attempts`, { cause: lastError });
}
console.log(
await retry(async (attempt) => {
if (attempt < 3) throw new Error("not yet");
return `ok on attempt ${attempt}`;
}),
);ok on attempt 3Retry only operations that are safe to repeat, add random jitter in production and always bound the number of attempts.
A concurrency limit. Promise.all starts everything. A pool of lanes runs a fixed number at a time.
async function mapLimit(items, limit, worker) {
const results = new Array(items.length);
let next = 0;
async function lane() {
while (next < items.length) {
const index = next++;
results[index] = await worker(items[index]);
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, lane));
return results;
}
let running = 0;
let peak = 0;
const output = await mapLimit([1, 2, 3, 4, 5], 2, async (n) => {
running += 1;
peak = Math.max(peak, running);
await sleep(5);
running -= 1;
return n * 10;
});
console.log(output, "peak:", peak);[ 10, 20, 30, 40, 50 ] peak: 2Memoizing a promise. Store the promise, not the value, so that callers arriving while a load is in flight share it instead of starting their own.
const cache = new Map();
function loadUser(id) {
if (!cache.has(id)) {
cache.set(
id,
sleep(5, { id }).catch((error) => {
cache.delete(id); // do not cache failures
throw error;
}),
);
}
return cache.get(id);
}
const [a, b] = await Promise.all([loadUser(1), loadUser(1)]);
console.log("same object:", a === b);same object: trueRunning promises in sequence from a list. A reduce over the list chains them, but a for...of loop with await reads better and does the same thing.
const tasks = [() => sleep(5, "a"), () => sleep(5, "b"), () => sleep(5, "c")];
const results = [];
for (const task of tasks) results.push(await task());
console.log(results);[ 'a', 'b', 'c' ]Testing promise code
Promise tests fail in two ways: they pass without checking anything, and they fail sometimes. The first happens when a test does not return or await its promise, so the runner finishes before the assertions run. Make every test async and await the work, and use assert.rejects for expected failures, which fails the test if the promise fulfills.
import test from "node:test";
import assert from "node:assert/strict";
test("fulfills with the parsed value", async () => {
assert.deepEqual(await Promise.try(() => JSON.parse('{"a":1}')), { a: 1 });
});
test("rejects on bad input", async () => {
await assert.rejects(Promise.try(() => JSON.parse("{bad")), SyntaxError);
});ā fulfills with the parsed value
ā rejects on bad inputThe second kind of failure comes from real time. Do not assert that something happened after exactly 100 ms. Wait on a promise you control, such as one from Promise.withResolvers, and use fake timers where the runner provides them. Assert the order and the kind of outcome, not exact durations. Stubs are easy with Promise.resolve(value) and Promise.reject(new Error("...")), and a deferred lets a test hold an operation open, inspect the in-between state and then finish it on its own terms.
Debugging promise code
When a chain behaves oddly, three techniques find most problems. First, insert a logging step that prints and returns its input, .then((value) => { console.log(value); return value; }), and move it along the chain until the printed value stops being what you expect. The step just before is the culprit, and it is usually a missing return. Second, if a chain never finishes, look for a promise that never settles, which is typically a callback wrapper where one branch forgot to call resolve or reject. A deadline helps here, since it turns a hang into a named timeout. Third, make dropped promises loud: lint for floating promises, and run tests with node --unhandled-rejections=strict, so a rejection nobody handled fails immediately and points at its source.
Stack traces after an await are rebuilt by the engine from the chain of awaiting async functions, and the rebuilding stops at timers, event emitters and promise plumbing that does not use await. Keep important paths in async and await, name your functions and wrap errors with a cause, as described in the post on async stack traces.
Mistakes to avoid
**Forgetting to
returnin athen.** The chain does not wait, the next step getsundefinedand failures go unhandled.Nesting instead of chaining. A
theninside athendisconnects the error path. Return the inner promise.Swallowing errors. A
catchthat logs and returns normally turns a failure into a success. Rethrow, or return a deliberate fallback.**Wrapping a promise in
new Promise.** If a function already returns a promise, return it. The constructor is for callback APIs.Using a promise for something that repeats. A promise settles once. Use an event emitter, an async iterator or an observable for repeated values.
Assuming laziness. A promise starts its work on creation. If you want to defer the work, wrap it in a function and call it later.
Unbounded fan-out. A promise per item in a long list overwhelms whatever it calls. Bound the concurrency.
Ignoring rejections of losers. After
raceorany, the other promises keep running, and their work is wasted unless you cancel it with a signal.Rejecting with strings. They carry no stack trace. Use
Errorobjects.**An accidental
thenmethod.** An object with a function namedthenis treated as a promise and may hang anawait.
When a promise is the wrong tool
A promise carries one result. For a sequence of values over time, such as clicks, messages or chunks of a file, use an event emitter, an async iterator or an observable, depending on whether the consumer or the producer sets the pace. For work that must be cancellable, use a promise together with an AbortSignal, because the promise alone cannot stop anything. For work that is mostly computation, no promise helps, since the computation runs on the thread whatever wraps it, and a worker is the remedy. For something that must happen right after the current code, with no asynchrony in between, a plain function call is simpler than any promise.
How resolution actually works
The words "resolve" and "fulfill" are often used as if they meant the same thing, and the difference explains behavior that otherwise looks odd. A promise is fulfilled when it holds a value, and rejected when it holds a reason. A promise is resolved when its fate is decided, which may be before it is settled. The distinction shows up when you resolve a promise with another promise.
When you call resolve(x) and x is a plain value, the promise is fulfilled with it. When x is a promise or a thenable, the promise is now "locked in" to following x: it is resolved, because nothing else can change its fate, but it is still pending until x settles, and then it copies the outcome. A second call to resolve or reject is ignored in both cases, because the promise's fate is already decided.
const inner = new Promise((resolve) => setTimeout(() => resolve("inner value"), 20));
const outer = new Promise((resolve, reject) => {
resolve(inner);
reject(new Error("ignored: already resolved to inner"));
});
console.log(outer);
console.log(await outer);Promise { <pending> }
inner valueouter stayed pending for twenty milliseconds, though resolve had already been called, and the later reject changed nothing. This is the rule that lets async functions return promises without nesting them. It also costs time. Following a thenable takes extra microtasks, which is why returning a native promise from a then handler takes a few more ticks than returning a plain value. The difference is invisible in most code and visible in tests that count ticks, which is a good reason not to write such tests.
One more consequence: a promise cannot be fulfilled with a promise. Whatever you try to fulfill it with, if it is a thenable, gets unwrapped, so await never gives you a promise of a promise, and code that expects one is mistaken.
Where promises appear in the platform
A large part of what you call every day returns a promise, and recognizing them helps you read documentation quickly. In the browser, fetch, response.json(), response.text(), Blob.arrayBuffer(), navigator.clipboard.writeText(), crypto.subtle.digest(), IndexedDB wrappers, import() expressions, the Notification.requestPermission() function, document.fonts.ready, HTMLMediaElement.play() and the whole of the Cache and Service Worker APIs return them. In Node.js, the node:fs/promises, node:timers/promises, node:dns/promises, node:stream/promises and node:readline/promises modules do, along with fetch, events.once(), child_process helpers wrapped with util.promisify and the test runner's tests.
Two points about these APIs are worth stating. First, many of them reject for ordinary failures, such as a missing file or a denied permission, and not only for programming errors, so you should expect to handle rejections as part of normal control flow. Second, a successful fetch promise does not mean a successful HTTP response. It fulfills for any response the server sends, including 404 and 500, and rejects only for network failures and aborts. Check response.ok and decide what a bad status means for your code.
const response = await fetch("data:text/plain,hello");
console.log(response.ok, response.status);
console.log(await response.text());true 200
helloThe data: URL keeps the example self-contained. In real code, a status of 404 would still give you a fulfilled promise with ok set to false, and a throw on !response.ok is the usual translation into a rejection.
Designing functions that return promises
If you write functions that other people will call, a few conventions make them pleasant to use and easy to compose.
Always return a promise, or never. A function that returns a promise in one branch and a plain value in another forces callers to handle both and hides bugs that appear only in the rarer branch. The simplest way to guarantee consistency is to declare the function async. If it must stay synchronous for other reasons, return Promise.resolve(value) in the quick branch.
Never throw synchronously from a function that returns a promise. A caller who wrote fn().catch(handler) will miss a synchronous throw. Validate arguments inside an async function or inside Promise.try, and all failures arrive through the promise.
**Reject with Error objects, with a stable code.** Messages change, and callers need something reliable to branch on. A code property such as ENOENT or E_TIMEOUT, or a subclass of Error, lets callers distinguish a missing record from a network failure without parsing text.
**Accept an AbortSignal for anything slow.** A { signal } option lets callers cancel and impose deadlines in the standard way, and it composes with the rest of the platform. Pass it down to every call that accepts one, and check it between steps that do not.
Do not start work in a constructor, and do not return a promise from one. A constructor cannot be async. Provide a static create() or open() method that returns a promise of the instance.
class Database {
#connection;
constructor(connection) {
this.#connection = connection;
}
static async open(url) {
const connection = await new Promise((resolve) => setTimeout(() => resolve({ url }), 5));
return new Database(connection);
}
get url() {
return this.#connection.url;
}
}
const db = await Database.open("db://local");
console.log(db.url);db://localDocument whether the work starts immediately. Since promises are eager, a function that returns a promise has already started its work by the time it returns. If you want callers to control when the work begins, return a function or a lazy object, and name it so.
Moving callback code to promises
Most code bases carry some callback code that predates promises. A calm way to move it over is to work from the outside in.
Start with the lowest-level wrapper. Convert the callback function once, with util.promisify or a small new Promise, and put it in one module. Everything above can then use the promise version, and you delete callbacks layer by layer without breaking callers. Keep the old callback function exported until nothing uses it.
Watch for three differences in behavior. A callback API may call its callback more than once, such as an event-like function, and a promise settles only once, so only the first call would count. A callback API may pass several results, and a promise holds one value, so return an object with named fields. And error handling changes shape: where a callback received (error, result), a promise rejects, and every call site needs a catch or a try.
import { promisify } from "node:util";
function legacyLookup(name, callback) {
setTimeout(() => {
if (name === "missing") callback(new Error("not found"));
else callback(null, { name, id: 7 });
}, 5);
}
const lookup = promisify(legacyLookup);
console.log(await lookup("ada"));
try {
await lookup("missing");
} catch (error) {
console.log(error.message);
}{ name: 'ada', id: 7 }
not foundAfter the conversion, call sites can use await and try/catch, and the callback pyramid disappears. The post on callbacks and callback hell shows the full before and after of such a migration.
Performance and memory, in terms you can reason about
A promise is a heap object with a state, a result and lists of handlers, and every then creates another one, so a long chain allocates one promise per step. For almost all code this does not matter, because the cost is small next to the I/O the promises represent. It matters in hot loops that create millions of promises, where an async function that never waits still allocates and defers, and in long-lived structures that hold promises, since a pending promise keeps its handlers, and everything those handlers reference, alive.
Two habits keep this in check. Do not use promises for work that is synchronous and cheap, since a plain function call is faster and clearer. And do not hold on to promises you no longer need, such as an entry in a cache map for a request that failed, since the entry keeps the rejection and its closure alive. Remove failed entries so the next caller retries.
Avoid explaining performance by guesswork. When someone claims that await is slower than then or that one combinator is faster than another, the honest answer is to explain the mechanism, such as the extra microtask for a thenable, and to measure your own workload before changing code for speed. The differences between the styles are small, and the cost of unreadable code is not.
Where promises sit among the alternatives
Promises are one of several ways to model "something will happen later", and the choice depends on how many values arrive and who is in control. A callback fits one-step operations and repeated events, and it is the base layer under the others. A promise fits a single result and composes well with async/await. An event emitter fits notifications with many listeners and no end. An async iterator fits a sequence that the consumer pulls at its own pace. An observable fits sequences that need operators such as debounce, retry and cancellation of stale work. The comparison, with the same task written each way, is in the post on event emitters, promises and observables.
If you are unsure, count the values. One value means a promise. More than one means one of the others. That single question prevents the most common misuse, a promise created for something that happens repeatedly, which settles on the first occurrence and ignores the rest.
A short history, and why it still matters
Promises were not invented for JavaScript. The idea of a placeholder for a future value is decades old, and several JavaScript libraries, among them jQuery's deferreds, Q and Bluebird, implemented their own versions in the early 2010s, each with slightly different behavior. The Promises/A+ specification, published in 2012, fixed the contract of then so that different implementations could interoperate, and ES2015 put a native Promise into the language, built on the same contract. Promise.prototype.finally arrived in ES2018, Promise.allSettled in ES2020, Promise.any in ES2021, Promise.withResolvers in ES2024 and Promise.try in ES2025.
The history explains two features that look odd today. Thenables exist because the contract was written to let libraries cooperate, and the language kept the rule when it adopted the standard. And the async/await syntax of ES2017 was designed as sugar over promises and not as a replacement, which is why every rule in this guide still applies to code that uses it. If you understand promises, you understand the machinery under await, and if you do not, await will keep surprising you in the places where it leaks through: unhandled rejections, ordering, return await and the extra ticks it costs.
It also explains why you will meet the old libraries' habits in existing code, such as a custom .done() method, a .spread() helper or a Promise.defer() object. These are not part of the standard. Convert them to native promises when you touch them, with Promise.resolve(thing) at the boundary, and the rest of your code can rely on the standard behavior.


