实现说明
功能封装在 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');