Promise Settle Paths Through then catch and finally

A rejection skips every then until one catch; handlers after the catch resume normally, and finally runs on both paths without changing the settled value.

JavascriptResilience

Code

javascriptsnippet
30 lines
// Rejection facts: late handlers still catch, observers replay the same reason.
// Each rejection is created after its first handler is registered, so nothing goes unhandled.
async function main() {
  const p = new Promise((_resolve, reject) => {
    setTimeout(() => reject(new Error("early failure")), 1);
  });

  p.catch((error) => console.log("caught:", error.message));
  // a second observer replays the settled rejection without new work
  p.catch(() => console.log("second observer"));

  // .then(onFulfilled) alone lets a rejection pass down the chain
  Promise.reject(new Error("pass through"))
    .then((v) => v)
    .catch((error) => console.log("chained:", error.message));

  // rejecting with a bare string is legal but carries no stack
  Promise.reject("plain string").catch((reason) => console.log("reason:", reason, typeof reason));

  // finally runs on both settle paths and must not change the settled value
  let observed = 0;
  const onSettled = () => { observed += 1; return "this return value is discarded"; };
  const ok = await Promise.resolve("payload").finally(onSettled);
  console.log("fulfilled:", ok, "| finally ran:", observed);
  const caught = await Promise.reject(new Error("boom")).catch((e) => e.message).finally(onSettled);
  console.log("rejected:", caught, "| finally ran:", observed);

  await new Promise((resolve) => setTimeout(resolve, 10));
}
await main();

Output

Captured from a sandboxed run of this snippet in the build pipeline.

reason: plain string string
chained: pass through
fulfilled: payload | finally ran: 1
rejected: boom | finally ran: 2
caught: early failure
second observer

Inside the snippet

Promise Settle Paths Through then catch and finally comes down to the functions onSettled and main.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Using it

The main signature reads const onSettled = ()

Running the file prints labeled results such as caught:, second observer, chained: — each operation’s effect is visible in the output.

Key statements

const caught = await Promise.reject(new Error("boom")).catch((e) => e.message).finally(onSettled);
const onSettled = () => { observed += 1; return "this return value is discarded"; };
const ok = await Promise.resolve("payload").finally(onSettled);

Interactive Tools for This Topic

FAQ

What does Promise Settle Paths Through then catch and finally print when run?
The script runs standalone; its 6 labeled outputs include `caught:`, `second observer`, `chained:`.