← 中文资源

简体中文版本

异步屏障放行分段启动

每个服务按自己的速度完成连接,然后在屏障前等待;最后一个到达者开门,所有等待方一起放行。慢服务不再拖住流程,快服务也不会先跑进下一阶段。

阅读英文原文

运行结果

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

search ready, waiting at the barrier
auth ready, waiting at the barrier
orders ready, waiting at the barrier
search passed the barrier together
auth passed the barrier together
orders passed the barrier together
stage complete, starting next phase

实现说明

底层就是函数 createBarrier、connectService、main。 异步流被 await 线性化,失败处理保持局部。 拿回来的是新对象,不是任何传入值的引用。

使用要点

  • 每一步打印都带着自己的标签:stage complete, starting next phase。
  • main 按顺序串起 createBarrier、connectService;运行文件就会把这个流程跑一遍。

常见问题

createBarrier 会修改传入的参数吗?

不会修改。入参只读,返回值是全新构造的。

运行「异步屏障放行分段启动」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 stage complete, starting next phase 这类标签。

主签名形如 function createBarrier(parties: number)

核心语句

await new Promise((resolve) => setTimeout(resolve, ms));
await Promise.all([
  connectService('auth', 20, stage),
  connectService('orders', 35, stage),
  connectService('search', 10, stage),
]);
const gate = Promise.withResolvers<void>();

代码示例

// One-shot async barrier: parties wait at the gate until all have
// arrived, then every waiter is released together
function createBarrier(parties: number) {
  let arrived = 0;
  const gate = Promise.withResolvers<void>();
  return {
    async wait(): Promise<void> {
      arrived += 1;
      if (arrived === parties) gate.resolve();
      await gate.promise;
    },
  };
}

async function connectService(
  name: string,
  ms: number,
  barrier: { wait(): Promise<void> },
) {
  await new Promise((resolve) => setTimeout(resolve, ms));
  console.log(name, 'ready, waiting at the barrier');
  await barrier.wait();
  console.log(name, 'passed the barrier together');
}

async function main() {
  // Staged startup: stage 1 finishes only when every service is connected
  const stage = createBarrier(3);
  await Promise.all([
    connectService('auth', 20, stage),
    connectService('orders', 35, stage),
    connectService('search', 10, stage),
  ]);
  console.log('stage complete, starting next phase');
}

main();