实现说明
功能封装在 KeyedLocks和函数 hold、main里。
这个文件只在 for (const line of order) console.log(line); 里循环。每个异步步骤都被 await,拒绝会在发起调用的那一行浮出。
使用要点
- 演示输出是带标签的(
idle keys left:),每个操作都会留下自己的一行标注。 main的演示流程是hold——跑一遍文件,这条流程从头到尾可见。
常见问题
运行「按键名串行化的异步锁」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 idle keys left: 标签标明各步骤。
主要签名是 function hold(key, ms, label)
核心语句
await new Promise((resolve) => setTimeout(resolve, ms));
await new Promise((resolve) => setTimeout(resolve, 0));
const previous = this.#tails.get(key) ?? Promise.resolve();
代码示例
// Keyed async locks: one tail promise per key. Same-key callers queue
// behind the previous holder; different keys never wait on each other.
class KeyedLocks {
#tails = new Map();
get size() {
return this.#tails.size;
}
runExclusive(key, task) {
const previous = this.#tails.get(key) ?? Promise.resolve();
const run = previous.then(() => task());
// The stored tail swallows rejections so one failing holder
// cannot poison the next waiter on the same key
const tail = run.catch(() => {});
this.#tails.set(key, tail);
tail.then(() => {
if (this.#tails.get(key) === tail) this.#tails.delete(key);
});
return run;
}
}
const locks = new KeyedLocks();
const order = [];
function hold(key, ms, label) {
return locks.runExclusive(key, async () => {
order.push(`${label} start`);
await new Promise((resolve) => setTimeout(resolve, ms));
order.push(`${label} end`);
});
}
async function main() {
await Promise.all([
hold('account:42', 30, 'a1'),
hold('account:42', 10, 'a2'),
hold('account:7', 10, 'b1'),
]);
// Let settlement bookkeeping microtasks finish before reading size
await new Promise((resolve) => setTimeout(resolve, 0));
for (const line of order) console.log(line);
console.log('idle keys left:', locks.size);
}
main();