Sub topic 3
Where using Is Allowed and What It Forbids
This chapter assumes you already know how using, await using, disposal order, and SuppressedError work. It covers the syntax limits, loops, disposable stacks, how to design your own resources, and the tooling you need.
Syntax Rules
A using declaration can go in a block, a function body, a for or for...of head, or the top level of a module. The binding behaves like const. It must have an initializer, and you cannot reassign it.
function demo(make) {
using a = make(); // allowed
{
using b = make(); // allowed in a nested block
}
// using c; // SyntaxError: missing initializer
// using { x } = make(); // SyntaxError: no destructuring
// a = make(); // TypeError: assignment to constant
}
demo(() => ({ [Symbol.dispose]() {} }));await using adds one more rule. It is only valid where await is valid: inside async functions and at the top level of a module. Neither form works at the top level of a classic script or in a for...in head.
Per-Iteration Resources
The loop for (using x of items) disposes each x at the end of the iteration that bound it, before the next value is taken. for await (await using x of items) does the same with async disposal.
DisposableStack
A DisposableStack collects cleanup work when the number of resources is only known at runtime. It has four main methods:
| Method | Purpose |
|---|---|
| `use(value)` | Registers a disposable and returns it |
| `adopt(value, fn)` | Registers a value that is not disposable, with `fn` as its cleanup |
| `defer(fn)` | Registers a plain callback |
| `move()` | Moves all registrations to a new stack, so the original stack has nothing left to dispose |
All registrations run in reverse order when the stack is disposed.
AsyncDisposableStack
An AsyncDisposableStack has the same API, but you dispose it with disposeAsync(). Its use method accepts both async and sync disposables.
async function openAll(names) {
await using stack = new AsyncDisposableStack();
for (const name of names) {
stack.use({
async [Symbol.asyncDispose]() { console.log(`close ${name}`); },
});
}
const owned = stack.move(); // setup succeeded, so hand off ownership
return { [Symbol.asyncDispose]: () => owned.disposeAsync() };
}
async function main() {
await using group = await openAll(["a", "b"]);
console.log("work");
}
main(); // work, close b, close aDesigning Your Own Resources
- Make dispose idempotent, so a second call does nothing.
- Throw from other methods once the object has been disposed.
- Return the resource from a factory that is already open, so callers can write
using x = open(). - Keep the resource's internal parts in a private
DisposableStackand forward to it from[Symbol.dispose].
Tooling Today
| Environment | Support |
|---|---|
| Chromium 134+, Node.js 24+, Firefox 141+ | Native support. Check Safari before relying on it. |
| TypeScript 5.2+ | Compiles the syntax down for older targets. Add `"esnext.disposable"` (or `"esnext"`) to `lib`. |
| Babel | Use `@babel/plugin-proposal-explicit-resource-management`. |
Older runtimes need a polyfill such as core-js for Symbol.dispose, SuppressedError, and both stack classes. Transpiling only handles the syntax.
{
"compilerOptions": {
"target": "es2022",
"lib": ["es2022", "esnext.disposable"]
}
}Exercise
Why does using conn = open(); fail at the top level of a classic <script> but work in a file loaded with type="module"?
Show answer
A using declaration is allowed at the top level of a module but not at the top level of a classic script. In a script you have to put it inside a block or a function.
Exercise
A setup function registers three resources on a DisposableStack and then returns. Why call move() before returning?
Show answer
Without move(), the using stack would dispose all three resources as soon as the function returns. Calling move() gives them to a new stack that the caller owns, so they stay open.