← 中文资源

简体中文版本

按键名串行化的异步锁

每个 key 维护一条尾部 Promise:同 key 的任务排队串行,不同 key 并发互不等待;尾部永不 reject,一次失败不会毒化后续等待者,key 空闲后自动清理条目防止泄漏。

阅读英文原文

运行结果

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

a1 start
b1 start
b1 end
a1 end
a2 start
a2 end
idle keys left: 0

实现说明

功能封装在 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();