实现说明
整个示例围绕函数 criticalSection组织。
异步流被 await 线性化,失败处理保持局部。非法状态在入口就被拒绝:抛出 Error,而不是带着坏数据继续。
使用要点
- 守卫
work === 'fail'满足时靠提前的throw短路流程。 - 演示输出是带标签的(
lock released、lock acquired:、caught:),每个操作都会留下自己的一行标注。
常见问题
输入非法时会怎样?
代码会拒绝继续:抛出 Error,此时状态仍可恢复。
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 criticalSection。
主要签名是 async function criticalSection(work)
核心语句
throw new Error('work failed while holding the lock');
await criticalSection('fail');
await using handle = lock;
代码示例
// Symbol.asyncDispose marks an object as an awaitable resource: `await using`
// calls it when the block exits and awaits the cleanup
const lock = {
acquired: false,
async [Symbol.asyncDispose]() {
this.acquired = false;
console.log('lock released');
},
};
async function criticalSection(work) {
await using handle = lock;
lock.acquired = true;
console.log('lock acquired:', handle.acquired);
if (work === 'fail') {
throw new Error('work failed while holding the lock');
}
return 'work done';
}
(async () => {
console.log(await criticalSection('ok'));
// Even a thrown error unwinds the resource before the exception propagates
try {
await criticalSection('fail');
} catch (err) {
console.log('caught:', err.message);
}
console.log('lock free again:', lock.acquired === false);
})();