using and Symbol.dispose — cleanup that runs when a block ends¶
Level: 301 · for anyone who has written try...finally to close something
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: using calls [Symbol.dispose]() as its block exits — in reverse order of declaration, even when the block throws — and when a dispose throws too, both errors survive in one SuppressedError; Node 24 and 25.2.1 run it without a flag.
Keywords: using, await using, Symbol.dispose, DisposableStack, SuppressedError
What the finished page will answer¶
- In what order do two
usingdeclarations dispose, and does disposal run when the block throws? - What do the
errorandsuppressedfields of aSuppressedErrorhold when both the block and a dispose throw? - What does
await usingwait for, and which symbol does it call? - What do
DisposableStack'suse,deferandmoveadd for resources that have no[Symbol.dispose]? - Why does tsc accept
usingunder--lib es2025only when@types/nodeis loaded? - What does
using x = nulldo, and what happens with a value that has no dispose method?
Examples it will need¶
-
explicit_resource_management_order_js.js— open and dispose lines for two using declarations, in a block that ends normally and in one that throws -
explicit_resource_management_suppressed_js.js— the SuppressedError when both the block and a dispose throw, with its error and suppressed messages -
explicit_resource_management_disposable_ts.ts— a class implementing Disposable, type-checked by tsc and run by node, printing open and dispose
See also¶
finally— the try...finally that using replaces- Well-known symbols — where Symbol.dispose sits among the other well-known symbols
- Async iteration — async cleanup, the setting for await using
WeakRefandFinalizationRegistry— cleanup you cannot schedule, beside cleanup you can- Rust:
Drop, and what RAII buys ↗ — the Rust version: Drop runs at the end of scope, no keyword needed - Rust: Drop guards ↗ — a value whose only job is cleanup on every exit
- Concurrency: Scoped locking ↗ — scoped cleanup applied to locks, across languages