JavaScript .then() and .catch(): Promise Error Handling Explained
Why this site is called ThenCatch: how promise chains pass values and errors along, and the mistakes that swallow them.
.then() and .catch() are the two methods most JavaScript developers meet first when working with promises. They are also where this site gets its name. This guide explains how a chain really behaves, so you stop losing errors and values along the way.
What a Promise Gives You
A promise is an object representing a value that is not available yet. It is in one of three states: pending, fulfilled with a value, or rejected with a reason. Once it settles it never changes. .then(onFulfilled, onRejected) registers callbacks, and .catch(fn) is shorthand for .then(undefined, fn).
fetch("/api/user/42")
.then((res) => res.json())
.then((user) => console.log(user.name))
.catch((err) => console.error("Request failed:", err));Handlers never run synchronously, even when the promise is already settled. They are queued as microtasks, which run after the current synchronous code finishes and before timers fire. This ordering surprises people who expect .then to behave like an immediate callback:
setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("then"));
console.log("sync");
// Output (Node 24):
// sync
// then
// timeoutThere are two ways to attach an error handler, and they are not equivalent. The second argument of .then(onFulfilled, onRejected) only handles rejections of the promise it is attached to. It does not catch an error thrown by the onFulfilled in that same call. A separate .catch after it does:
Promise.resolve()
.then(
() => { throw new Error("thrown in onFulfilled"); },
(err) => console.log("onRejected saw:", err.message) // does not run
)
.catch((err) => console.log("catch saw:", err.message));
// Output:
// catch saw: thrown in onFulfilledThis is the practical reason to prefer a trailing .catch over the two-argument form: it covers failures in the handler before it as well as in the original promise.
Every .then() Returns a New Promise
This is the rule that explains almost everything. Whatever a handler returns becomes the value of the next promise in the chain. Return a plain value and the next .then receives it. Return a promise and the chain waits for it. Return nothing and the next handler receives undefined.
Promise.resolve(2)
.then((n) => n * 2) // 4
.then((n) => Promise.resolve(n + 1)) // waits, then 5
.then((n) => { console.log(n); }) // logs 5, returns undefined
.then((n) => console.log(n)); // logs undefined
// Output:
// 5
// undefinedOne more detail: if you pass something that is not a function to .then, it is ignored and the value passes straight through. .then(somePromise) is a classic typo for .then(() => somePromise):
Promise.resolve("kept")
.then(null) // non-function: value passes through
.then(Promise.resolve("ignored")) // a promise is not a function either
.then((v) => console.log(v));
// Output:
// keptHow Errors Travel
A rejection, or an exception thrown inside any handler, skips every following .then until it reaches a .catch. That is why one .catch at the end can cover the whole chain.
Promise.resolve()
.then(() => { throw new Error("step 1 failed"); })
.then(() => console.log("never runs"))
.catch((err) => {
console.log(err.message); // "step 1 failed"
return "recovered";
})
.then((v) => console.log(v)); // "recovered"Note the last line: a .catch that returns a value turns the chain back into a fulfilled one. If you want the error to keep propagating, rethrow it.
Where you place .catch matters
A .catch in the middle of a chain handles the errors from everything above it, and the chain carries on below it. That is useful for optional steps but dangerous when you meant to stop. Run both variants to see the difference:
Promise.reject(new Error("first"))
.catch((e) => console.log("early catch:", e.message))
.then(() => console.log("next then still runs"));
Promise.reject(new Error("second"))
.catch((e) => { console.log("logged:", e.message); throw e; })
.then(() => console.log("skipped"))
.catch((e) => console.log("downstream also sees:", e.message));
// Output (the two chains interleave):
// early catch: first
// logged: second
// next then still runs
// downstream also sees: secondRule of thumb: put one .catch at the end for the whole chain, and add a mid-chain .catch only when you deliberately want a fallback value and to continue.
finally()
.finally(fn) runs whether the promise fulfilled or rejected, receives no arguments, and passes the original result or error through unchanged. Use it for cleanup such as hiding a spinner or releasing a lock, not for transforming values. Its return value is ignored, with one exception: if the finally callback itself throws or returns a rejected promise, that rejection replaces the original result.
showSpinner();
fetch("/api/report")
.then((r) => r.json())
.catch(handleError)
.finally(hideSpinner);
// Passing through, and the throwing exception:
Promise.resolve("val").finally(() => "ignored").then((v) => console.log("passes through:", v));
Promise.resolve(1).finally(() => { throw new Error("from finally"); })
.catch((e) => console.log("finally can still throw:", e.message));
// Output:
// finally can still throw: from finally
// passes through: valMistakes That Swallow Errors
1. Forgetting to return
// Bug: the inner promise is not returned, so the chain does not wait
// and its rejection escapes the .catch below
getUser().then((u) => { saveUser(u); }).catch(log);
// Fix
getUser().then((u) => saveUser(u)).catch(log);Here is the bug in a runnable form. The chain reports success before the work finishes, the .catch never fires, and the failure surfaces as an unhandled rejection:
const failLater = () =>
new Promise((_, reject) => setTimeout(() => reject(new Error("save failed")), 5));
process.on("unhandledRejection", (reason) =>
console.log("unhandledRejection:", reason.message));
Promise.resolve()
.then(() => { failLater(); }) // no return
.then(() => console.log("chain finished early"))
.catch((err) => console.log("catch:", err.message));
// Output:
// chain finished early
// unhandledRejection: save failed
//
// With .then(() => failLater()) the output is instead:
// catch: save failed2. Nesting instead of chaining
Nested .then calls recreate callback hell and make error flow hard to follow. Return the inner promise and keep the chain flat. A nested chain also needs its own .catch, because the outer one cannot see into promises you did not return.
3. A .catch that hides failure
.catch(() => {}) turns every error into silence. At minimum log it. If the caller needs to know, rethrow.
4. Treating HTTP errors as rejections
fetch rejects only when the request itself fails, for example on a network error or a malformed URL. A 404 or 500 still fulfils, so check res.ok yourself:
fetch(url).then((res) => {
if (!res.ok) throw new Error("HTTP " + res.status);
return res.json();
});Not sure what a status code means? See HTTP status codes explained, or test an endpoint directly in the API Tester.
5. Async callbacks inside forEach
Array.prototype.forEach ignores the promises its callback returns, so nothing waits for them and their errors escape any surrounding try or .catch. Use for...of with await for sequential work, or Promise.all with map for parallel work:
// run as an ES module (top-level await)
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
let done = false;
[1, 2, 3].forEach(async (n) => { await wait(20); done = true; });
console.log("right after forEach, done =", done);
await Promise.all([1, 2, 3].map(async () => { await wait(20); }));
console.log("after Promise.all(map), awaited");
// Output:
// right after forEach, done = false
// after Promise.all(map), awaited6. Unhandled rejections
A rejected promise with no handler triggers an unhandledrejection event in browsers and, in Node.js 15 and later, crashes the process by default (the default mode is throw). Always end a chain with a .catch or return it to a caller that has one. In Node you can observe the leaks with process.on("unhandledRejection", ...), and in browsers with window.addEventListener("unhandledrejection", ...). Use these as a safety net for logging, not as a substitute for handling errors where they happen.
Running Promises Together
Promise.all([a(), b()]) // rejects as soon as any rejects
Promise.allSettled([a(), b()]) // always resolves, one result per promise
Promise.race([a(), b()]) // first to settle wins
Promise.any([a(), b()]) // first to fulfil, rejects only if all rejectChoose allSettled when partial success is acceptable, for example loading several independent widgets. Here they are on real tasks, where task B fails after 10 ms:
// run as an ES module (top-level await)
const task = (name, ms, fail = false) =>
new Promise((resolve, reject) =>
setTimeout(() => (fail ? reject(new Error(name)) : resolve(name)), ms));
console.log("all:", await Promise.all([task("A", 30), task("C", 20)]));
await Promise.all([task("A", 30), task("B", 10, true)])
.catch((e) => console.log("all rejected with:", e.message));
const settled = await Promise.allSettled([task("A", 30), task("B", 10, true)]);
console.log("allSettled:", settled.map((r) =>
r.status === "fulfilled" ? r.value : "rejected: " + r.reason.message));
console.log("race:", await Promise.race([task("A", 30), task("C", 10)]));
console.log("any:", await Promise.any([task("B", 10, true), task("C", 20)]));
await Promise.any([task("B", 10, true), task("D", 20, true)]).catch((e) =>
console.log(e.name + ":", e.errors.map((x) => x.message)));
// Output:
// all: [ 'A', 'C' ]
// all rejected with: B
// allSettled: [ 'A', 'rejected: B' ]
// race: C
// any: C
// AggregateError: [ 'B', 'D' ]Two things to remember. First, when Promise.all rejects, the other promises are not cancelled. They keep running and their results are simply discarded. Second, Promise.race settles with whichever promise settles first, including a rejection, which makes it a convenient way to add a timeout:
const withTimeout = (promise, ms) =>
Promise.race([
promise,
new Promise((_, reject) =>
setTimeout(() => reject(new Error("timed out after " + ms + "ms")), ms)),
]);
const slow = new Promise((resolve) => setTimeout(() => resolve("done"), 50));
withTimeout(slow, 10).catch((err) => console.log(err.message));
// Output:
// timed out after 10msThe losing promise is not cancelled here either. To actually abort a fetch, pass it an AbortSignal.
.then() vs async/await
async/await is syntax over the same promises. The same chain reads like this:
async function loadUser(id) {
try {
const res = await fetch("/api/user/" + id);
if (!res.ok) throw new Error("HTTP " + res.status);
return await res.json();
} catch (err) {
console.error(err);
throw err;
} finally {
hideSpinner();
}
}Prefer await for sequential logic with branches and loops. Prefer .then for short transformations and when composing promises without an async function. They mix freely, because an async function returns a promise.
| Task | .then / .catch | async / await |
|---|---|---|
| Handle an error | .catch(fn) | try / catch |
| Cleanup | .finally(fn) | finally |
| Pass a value on | return from the handler | assign the awaited result |
| Run in parallel | Promise.all([...]) | await Promise.all([...]) |
| Forgotten step | missing return | missing await |
The async/await mirror of the forgotten return is a forgotten await: the function carries on while the promise runs unobserved, and its rejection is unhandled. Also remember that sequential await calls run one after another. If the calls are independent, start them together and await the combined result.
Debugging a Broken Chain
- Check that every handler that calls something asynchronous returns it.
- Log the value at the top of each
.then. Anundefinedusually means a missingreturn. - Log
errin the.catchitself. Rejections are not alwaysErrorobjects, so look aterr.messageand the raw value. - Inspect the promise in the console. It prints as
Promise { <pending> },<rejected>or the fulfilled value, which tells you whether it settled at all. - For network calls, confirm the status and body in the API Tester before blaming the chain. The API debugging guide walks through this workflow, and CORS explained covers the browser-only rejections that show up as a generic network error.
Quick Reference
- Each
.thenreturns a new promise. Return values to pass them on. - A throw or rejection skips to the nearest
.catch. - A
.catchthat returns normally recovers the chain. .finallyis for cleanup and does not change the result.fetchdoes not reject on HTTP error statuses.- Every chain should end in a handler.
- Handlers run as microtasks, after synchronous code and before timers.
Promise.allandPromise.racedo not cancel the losers.
Frequently Asked Questions
What is the difference between .then().catch() and .then(a, b)?
With .then(onFulfilled, onRejected), the rejection handler only sees failures of the original promise, not errors thrown by onFulfilled. A trailing .catch sees both, which is why it is the usual choice.
Does .catch() return a promise?
Yes. .catch(fn) returns a new promise that fulfils with whatever fn returns, or rejects if fn throws. That is why a chain can continue after a .catch.
Why does my .catch() not run when fetch gets a 404?
fetch rejects only when the request itself fails (network error, malformed URL, abort). A 404 or 500 is a completed HTTP exchange, so you must check res.ok or res.status and throw yourself.
Should I use .then() or async/await?
Both produce the same promises, so pick for readability. Use await for multi-step logic with branches or loops, and .then for short transformations. Mixing them is fine.
How do I handle errors in Promise.all?
Promise.all rejects with the first rejection, so attach a .catch or wrap the await in try/catch. If you need every result regardless of failures, use Promise.allSettled and inspect each entry's status.
When the data coming out of a promise needs inspecting, the JSON Editor and JWT Decoder are useful next stops.
Written by Kashyap Thakar
Spotted a mistake? Let me know