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.
Code
// 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 blockInside 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
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches.
Report a problem with this exampleOpens a pre-filled issue on GitHub.