← 中文资源

简体中文版本

Promise 结算路径 then catch finally

拒绝会跳过所有 then 直到最近的 catch,catch 之后的处理链恢复正常;finally 在兑现与拒绝两条路径上都执行、返回值被丢弃,不改变结算值;多个观察者回放同一次结算结果而不重复执行,裸字符串拒绝合法但失去栈信息。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

除了函数 onSettled、main,文件里再无其他定义。 await 标出每个异步边界——没有 fire-and-forget。

使用要点

  • 直接运行文件,输出会带上标签,比如 caught:、second observer、chained:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「Promise 结算路径 then catch finally」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 caught:、second observer、chained: 标签标明各步骤。

入口签名:const onSettled = ()

核心语句

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);

代码示例

// 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();