using Declarations Dispose Deterministically
Scope resources with using declarations: [Symbol.dispose] runs in reverse declaration order on block exit, on both normal and throwing paths.
Code
// using 声明:块结束时按声明的逆序自动调用 [Symbol.dispose]
const log = [];
class ScopedFile {
constructor(name) {
this.name = name;
log.push('open ' + name);
}
[Symbol.dispose]() {
log.push('close ' + this.name);
}
}
{
using a = new ScopedFile('config.toml');
using b = new ScopedFile('secrets.env');
log.push('use both');
}
// 块内抛错也一样:已打开的资源按逆序释放,错误继续向外传播
try {
using c = new ScopedFile('cache.db');
throw new Error('boom');
} catch {
log.push('caught boom');
}
console.log(log.join(', '));
console.log('symbol.dispose:', typeof Symbol.dispose);Output
Captured from a sandboxed run of this snippet in the build pipeline.
open config.toml, open secrets.env, use both, close secrets.env, close config.toml, open cache.db, close cache.db, caught boom
symbol.dispose: symbolHow the snippet works
Count the class ScopedFile as the entire surface area of using Declarations Dispose Deterministically.
The Error throw sits inside a try: execution reaches it unconditionally, and the surrounding handler catches it.
The file’s state is a handful of top-level bindings: log.
Applying it
Each run prints the 1 labeled block symbol.dispose: in source order.
Statements that matter
throw new Error('boom');
Interactive Tools for This Topic
FAQ
- Does the snippet validate its input?
- No — the `Error` is raised inside a `try` block: execution reaches it unconditionally, and the surrounding handler clause decides what catches it. There is no input check in the snippet.
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. Its state lives in module-level bindings: `log`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.