← 中文资源

简体中文版本

await using 异步资源释放

await using 声明可异步释放的资源:离开作用域自动调用 Symbol.asyncDispose,即使块内抛错也会先释放再向外传播,替代手写 try/finally。

阅读英文原文

运行结果

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

open: primary
primary: select 1
dispose: primary
after block

实现说明

功能封装在 LeasedConnection里。 异步流被 await 线性化,失败处理保持局部。

使用要点

  • 直接运行文件,输出会带上标签,比如 open:、dispose:、after block——输出的每一行都能指回产生它的那次调用。

常见问题

运行前要先安装什么?

什么都不用额外装——运行时自带了代码所需的一切。

核心语句

await using conn = new LeasedConnection('primary');
async [Symbol.asyncDispose](): Promise<void> {
  this.opened = false;
  console.log('dispose:', this.name);
}
return `${this.name}: ${sql}`;

代码示例

// await using: 显式资源管理,离开作用域时确定性释放异步资源
class LeasedConnection {
  name: string;
  opened = false;

  constructor(name: string) {
    this.name = name;
    this.opened = true;
    console.log('open:', name);
  }

  async [Symbol.asyncDispose](): Promise<void> {
    this.opened = false;
    console.log('dispose:', this.name);
  }

  query(sql: string): string {
    return `${this.name}: ${sql}`;
  }
}

{
  await using conn = new LeasedConnection('primary');
  console.log(conn.query('select 1'));
  // 即使块内抛错,dispose 也会先执行再向外传播
}
console.log('after block');