Promise Chain Errors Propagate To One Catch

A rejection skips every then until the nearest catch, so one handler covers a whole chain and a returned value marks the chain recovered.

JavascriptResilience

Code

javascriptsnippet
20 lines
// 链上任何一步抛错:后续 then 全部跳过,rejection 沿链传到最近的 catch
const ok = await Promise.resolve('{"qty":2}')
  .then((text) => JSON.parse(text))
  .then((data) => data.qty * 100)
  .then((cents) => `charge ${cents} cents`);
console.log(ok);

// JSON.parse 抛出的 SyntaxError 被链尾的 catch 接住,中间步骤不再执行
const failed = await Promise.resolve('not-json')
  .then((text) => JSON.parse(text))
  .then((data) => data.qty * 100)
  .then((cents) => `charge ${cents} cents`)
  .catch((error) => `failed: ${error.name}`);
console.log(failed);

// catch 返回普通值即恢复 fulfilled,链可以继续走下去
const recovered = await Promise.reject(new Error('boom'))
  .catch((error) => error.message.toUpperCase())
  .then((message) => `recovered from ${message}`);
console.log(recovered);

Output

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

charge 200 cents
failed: SyntaxError
recovered from BOOM

How it works

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

The file’s state is a handful of top-level bindings: ok, failed, recovered.

Key statements

.then((message) => `recovered from ${message}`);
const ok = await Promise.resolve('{"qty":2}')
.then((text) => JSON.parse(text))
.then((data) => data.qty * 100)
.then((cents) => `charge ${cents} cents`);
.catch((error) => `failed: ${error.name}`);

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. Its state lives in module-level bindings: `ok`, `failed`, `recovered`.