Sub topic 11
Managing Groups of Resources with DisposableStack
This chapter assumes you know the using declaration, the order in which resources are disposed, and how SuppressedError reports failures during cleanup. A using declaration works well when you know at write time how many resources a block holds. It falls short when that number depends on runtime data, when some resources are optional, or when a value has a cleanup function but no Symbol.dispose method. DisposableStack covers those cases.
The working model
A DisposableStack is a container that is itself disposable. You register resources and cleanup callbacks with it. When the stack is disposed, it runs every registered cleanup in reverse order of registration, the same last-in, first-out rule that using follows. Declaring the stack with using ties the whole group to one scope.
| Method | What it registers | Returns |
|---|---|---|
| `use(value)` | A disposable object; `null` and `undefined` are skipped | `value` |
| `adopt(value, onDispose)` | Any value plus a callback that receives it | `value` |
| `defer(onDispose)` | A callback with no argument | `undefined` |
| `move()` | Nothing; it transfers everything to a new stack | the new `DisposableStack` |
| `dispose()` | Nothing; it runs all cleanups now | `undefined` |
The disposed getter reports whether the stack has already been disposed. Calling dispose() a second time does nothing.
A dynamic number of resources
This function opens a list of files. If any open fails, the files that already opened must be closed, and on success the caller must own all of them.
function openFile(name) {
if (name === "bad") throw new Error(`cannot open ${name}`);
console.log(`open ${name}`);
return { name, [Symbol.dispose]() { console.log(`close ${name}`); } };
}
function openAll(names) {
using stack = new DisposableStack();
const files = names.map((n) => stack.use(openFile(n)));
const owned = stack.move(); // success: hand everything to the caller
return { files, [Symbol.dispose]() { owned.dispose(); } };
}
{
using group = openAll(["a", "b", "c"]);
console.log(group.files.map((f) => f.name).join(","));
}
// open a, open b, open c, a,b,c, close c, close b, close a
try {
openAll(["x", "bad", "y"]);
} catch (e) {
console.log(e.message);
}
// open x, close x, cannot open badThe key line is stack.move(). It creates a fresh stack holding every registered resource and marks the original stack as disposed. When openAll returns, the using stack declaration disposes the now-empty original, so nothing is closed. If openFile throws before move() runs, the original stack still holds the files opened so far and closes them as the exception leaves the function.
Adapting APIs that are not disposable
Timer IDs, event listeners, and older library handles have no Symbol.dispose method. You can wrap them with adopt and defer without writing a wrapper class.
const stack = new DisposableStack();
const id = stack.adopt(setInterval(() => {}, 1000), (t) => clearInterval(t));
stack.defer(() => console.log("listeners removed"));
console.log(typeof id); // "object" in Node, "number" in browsers
stack.dispose(); // logs "listeners removed", then clears the interval
console.log(stack.disposed); // trueUse adopt when the cleanup needs the value. Use defer for side-effect cleanup that needs no value.
Common errors
- Using a stack after
move()ordispose(). Callinguse,adopt,defer, ormoveon a disposed stack throws aReferenceError. Callmove()last. - Passing a non-disposable to
use. An object without a callableSymbol.disposethrows aTypeErrorright away. Useadoptfor such objects. - Forgetting
usingon the stack. A stack held in aconstis never disposed automatically, so the code leaks unless something callsdispose(). - Expecting cleanup to stop at the first error. The stack runs every callback. If several throw, the errors are chained into a
SuppressedError, the same wayusingreports them.
Exercise
A function runs using stack = new DisposableStack(), then stack.defer(() => console.log("A")), then stack.use(r) where r logs "R" on dispose, then stack.defer(() => console.log("B")), and returns normally without calling move(). What prints when it returns, and what would print if stack.move() were called just before the return?
Show answer
Without move(), it prints B, R, A, in reverse order of registration. With move(), nothing prints at return, because the original stack is empty. The returned stack prints B, R, A when the caller disposes it.
Exercise
Why does stack.use(setTimeout(() => {}, 100)) fail, and how do you fix it?
Show answer
The timer handle has no Symbol.dispose method, so use throws a TypeError. Write stack.adopt(setTimeout(() => {}, 100), (t) => clearTimeout(t)) instead.