Async Disposal With await using

Release async resources deterministically with await using and Symbol.asyncDispose, which runs when the block exits even if the body throws.

TypescriptResilience

Code

typescriptsnippet
27 lines
// 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');

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

Inside the snippet

Async Disposal With await using comes down to the class LeasedConnection.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Putting it to use

Running the file prints labeled results such as open:, dispose:, after block — each operation’s effect is visible in the output.

Core lines

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

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches.