Promise Chaining and Error Handling in JavaScript: Returning Values, catch Placement, finally and Unhandled Rejections
Master promise chains: why every then returns a new promise, how returned values and promises flow to the next step, the forgotten-return bug, how errors skip ahead to catch, recovering and rethrowing, finally semantics, then(a, b) vs then(a).catch(b), unhandled rejections and retry patterns.
kvi5hnuCode Sprout team member7 min readOn this page
Article 95 showed single promises. Their real power appears when you chain them: each step's result feeds the next, and one catch at the end handles a failure anywhere in the sequence. This turns the nested "pyramid of doom" from article 94 into a flat, readable list of steps. It's also where most promise bugs live, so this article goes through the rules carefully.
Every then returns a new promise
then, catch and finally don't return the promise you called them on. They return a new promise, which settles based on what your callback does:
| Your callback... | The promise returned by then is... |
|---|---|
returns a value v | fulfilled with v |
| returns nothing | fulfilled with undefined |
returns a promise (or thenable) p | resolved to p: it waits for p and settles the same way |
throws an error e | rejected with e |
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
const first = Promise.resolve(2);
const second = first.then((x) => x * 10);
console.log(first === second);
second
.then((x) => delay(10, x + 1)) // returns a promise: the chain waits 10 ms
.then((x) => console.log("result", x));
false
result 21
The third step received 21, not a promise: when a callback returns a promise, the next step waits for it and receives its value. This is the "resolved" state from article 95 in action, and it's what lets a chain express "do A, then B, then C" for asynchronous A, B and C.

Sequential steps without nesting
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
const fetchUser = (id) => delay(10, { id, name: "Ana" });
const fetchOrders = (user) => delay(10, [`order-1 for ${user.name}`, `order-2 for ${user.name}`]);
const formatReport = (orders) => `${orders.length} orders: ${orders.join(", ")}`;
fetchUser(7)
.then((user) => fetchOrders(user))
.then((orders) => formatReport(orders))
.then((report) => console.log(report))
.catch((err) => console.log("failed:", err.message));
2 orders: order-1 for Ana, order-2 for Ana
Compare this with nested callbacks: each step is at the same indentation level, and one catch covers all of them. When a function's parameter is exactly the previous value, you can pass it directly: .then(fetchOrders).then(formatReport).
Don't nest promises
A common beginner pattern recreates callback hell inside then:
// avoid: nested
fetchUser(7).then((user) => {
fetchOrders(user).then((orders) => {
render(orders);
});
});
// prefer: flat, and errors from fetchOrders reach the catch
fetchUser(7)
.then(fetchOrders)
.then(render)
.catch(showError);
Nesting is only needed when a later step needs two earlier results (both user and orders). Even then, async/await (article 98) is usually the cleaner answer.
The forgotten return
The most common promise bug: a then callback with a block body that starts async work but doesn't return it.
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
Promise.resolve("ana")
.then((user) => {
delay(5, `${user}'s orders`); // started, but not returned
})
.then((orders) => console.log("without return:", orders));
Promise.resolve("ana")
.then((user) => {
return delay(5, `${user}'s orders`);
})
.then((orders) => console.log("with return:", orders));
without return: undefined
with return: ana's orders
Without return, the next step runs immediately with undefined, doesn't wait for the work, and any error from that work escapes the chain entirely, becoming an unhandled rejection. Arrow functions with expression bodies ((user) => delay(...)) return automatically; adding braces removes the automatic return, which is how this bug usually creeps in.
How errors travel
A rejection (from a rejected promise or a throw inside any callback) skips every following then success handler until it reaches a catch:
Promise.resolve(1)
.then(() => {
throw new Error("step 2 failed");
})
.then(() => console.log("step 3 (skipped)"))
.then(() => console.log("step 4 (skipped)"))
.catch((err) => console.log("caught:", err.message))
.then(() => console.log("the chain continues after catch"));
caught: step 2 failed
the chain continues after catch
This is the promise version of try...catch: the chain is the try block and catch is the catch clause. Thrown errors inside then callbacks are caught automatically, so even bugs (like a TypeError from reading a property of undefined) end up in your catch.
Recovering and rethrowing
What a catch callback returns decides what happens next, by the same rules as then:
const primary = () => Promise.reject(new Error("primary server down"));
primary()
.catch((err) => {
console.log("recovering from:", err.message);
return { source: "cache", items: [] }; // recover: chain continues fulfilled
})
.then((data) => console.log("using data from", data.source));
Promise.reject(new TypeError("bad input"))
.catch((err) => {
if (!(err instanceof RangeError)) throw err; // not ours to handle: rethrow
return "handled range error";
})
.catch((err) => console.log("outer handler got", err.name));
recovering from: primary server down
using data from cache
outer handler got TypeError
- Return a value from
catchto recover; the chain continues as fulfilled. - Throw (or return a rejected promise) to keep it rejected, for example to rethrow errors you don't know how to handle, or to wrap them:
throw new Error("Could not load report", { cause: err }). - A
catchthat only logs and returns nothing swallows the error: later steps run withundefined. Make sure that's what you want.
Where to put catch
Placement matters:
// one catch for the whole chain: any failure skips to it
load().then(parse).then(render).catch(showError);
// catch in the middle: provides a fallback, then continues
load()
.catch(() => loadFromCache()) // only load() failures are handled here
.then(parse)
.then(render)
.catch(showError); // anything else
then(onFulfilled, onRejected) vs then().catch()
then accepts a rejection handler as its second argument, but it only handles errors from earlier steps, not from the success handler next to it:
Promise.resolve("data")
.then(
() => { throw new Error("bug in success handler"); },
() => console.log("not called: this only sees earlier rejections"),
)
.catch((err) => console.log("caught by catch:", err.message));
caught by catch: bug in success handler
Prefer .then(onSuccess).catch(onError). Use the two-argument form only when you deliberately want different handling for "the earlier step failed" and "my success handler failed".
finally
finally(callback) runs when the promise settles either way, receives no arguments, and normally passes the original outcome through:
Promise.resolve("report")
.finally(() => "this return value is ignored")
.then((v) => console.log("value passed through:", v));
Promise.reject(new Error("load failed"))
.finally(() => console.log("spinner hidden"))
.catch((err) => console.log("error passed through:", err.message));
Promise.resolve("report")
.finally(() => {
throw new Error("cleanup failed");
})
.catch((err) => console.log("finally can override:", err.message));
spinner hidden
finally can override: cleanup failed
value passed through: report
error passed through: load failed
The one exception: if the finally callback throws (or returns a rejected promise), that error replaces the original outcome. If it returns a promise, the chain waits for it before continuing.
(The output order shows the three chains interleaving; each chain on its own runs top to bottom.)
Unhandled rejections
A rejected promise with no rejection handler is an unhandled rejection, and it's always a bug:
- Browsers log "Uncaught (in promise)" in the console and fire an
unhandledrejectionevent onwindow, which error monitoring tools listen to. - Node.js (since version 15) treats it like an uncaught exception: it prints the error and exits the process with a non-zero code. You can observe them with
process.on("unhandledRejection", ...), but that's for logging, not a substitute for handling errors.
process.on("unhandledRejection", (reason) => {
console.log("unhandled:", reason.message);
});
Promise.reject(new Error("nobody is listening"));
unhandled: nobody is listening
Rules that prevent them:
- Every chain ends with a
catch(or is returned to a caller that handles it, or awaited insidetry). - Always return promises from
thencallbacks, so inner failures join the chain. - Attach handlers promptly. A promise that rejects before any handler is attached counts as unhandled, even if you add a
catchlater.
window.addEventListener("unhandledrejection", (event) => {
reportToMonitoring(event.reason); // browser-side safety net
});
Pattern: retry with backoff
Chaining plus recursion gives a clean retry helper. Each failure waits a little longer before trying again:
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function retry(operation, attempts = 3, wait = 10) {
return operation().catch((err) => {
if (attempts <= 1) throw err;
console.log(`failed (${err.message}), retrying in ${wait} ms`);
return delay(wait).then(() => retry(operation, attempts - 1, wait * 2));
});
}
let calls = 0;
const flaky = () => (++calls < 3 ? Promise.reject(new Error(`attempt ${calls}`)) : Promise.resolve("ok"));
retry(flaky).then((result) => console.log(result, "after", calls, "calls"));
failed (attempt 1), retrying in 10 ms
failed (attempt 2), retrying in 20 ms
ok after 3 calls
Running a dynamic list of steps in sequence
When the number of steps is only known at run time, build the chain with reduce:
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
const upload = (file) => delay(5, `${file} uploaded`);
const files = ["a.png", "b.png", "c.png"];
files
.reduce(
(chain, file) => chain.then((results) => upload(file).then((r) => [...results, r])),
Promise.resolve([]),
)
.then((results) => console.log(results));
[ 'a.png uploaded', 'b.png uploaded', 'c.png uploaded' ]
Each upload starts only after the previous one finishes. With async/await, the same thing is a plain for...of loop (article 98); to run them at the same time instead, use Promise.all (article 97).
Common questions
Why does my second then receive undefined?
The previous callback didn't return anything, usually because it has a block body ({ ... }) without a return. Return the value or the promise.
Do I need a catch after every then?
No. One catch at the end handles failures from every earlier step. Add a catch in the middle only when you want to recover and continue.
Is throwing inside then the same as returning Promise.reject?
Yes, in effect: both reject the promise returned by then. Throwing is simpler and also catches accidental errors in your code.
Why does Node crash on an unhandled rejection?
Since Node 15, the default --unhandled-rejections=throw mode treats them like uncaught exceptions, because a silently ignored failure usually leaves the program in a broken state. Handle the error instead of changing the mode.
Summary
then,catchandfinallyeach return a new promise, settled by what the callback returns or throws.- Returning a promise makes the chain wait for it; the next step receives its value.
- Forgetting
returnin a block-bodied callback breaks sequencing and lets errors escape. - A rejection or throw skips following success handlers until a
catch;catchrecovers by returning a value, or rethrows. - Prefer
.then(a).catch(b)over.then(a, b);finallypasses results through unless it throws. - Every chain needs error handling: unhandled rejections are logged in browsers and crash Node.
Practice Questions
What does this print?
Promise.resolve(1)
.then((x) => x + 1)
.then((x) => { x * 10; })
.then((x) => console.log(x));
Answer
undefined. The second callback has a block body and no return, so the third step receives undefined.
What does this print, and in what order?
Promise.reject(new Error("A"))
.then(() => console.log("B"))
.catch((e) => { console.log("C", e.message); return "D"; })
.then((v) => console.log("E", v))
.finally(() => console.log("F"));
Answer
C A, then E D, then F. The rejection skips B; catch recovers by returning "D"; finally runs at the end.
Rewrite this nested code as a flat chain with a single error handler.
getUser(1).then((user) => {
getPosts(user.id).then((posts) => {
show(posts);
});
});
Answer
getUser(1)
.then((user) => getPosts(user.id))
.then((posts) => show(posts))
.catch((err) => showError(err));
Returning getPosts(...) from the first callback makes the chain wait for it, and errors from either request reach the catch.
Which errors does onError handle in snippet A, and which in snippet B?
load().then(render, onError);
load().then(render).catch(onError);
Answer
In snippet A, only rejections from load(); an error thrown inside render is unhandled. In snippet B, both load() failures and errors thrown inside render.
Previous: JavaScript Promises Explained: States, then, catch, finally and Creating Promises
Next: Promise.all, allSettled, race and any: Running Promises in Parallel in JavaScript

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.