实现说明
除了函数 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();