Sub topic 11
Managing Groups of Resources with DisposableStack
A using declaration works well when you know, while writing the code, exactly which resources a block needs. Real code often doesn't know that. A function might open a file only when a flag is set, open one connection per item in an array, or build several resources in a constructor that must all be released together later. DisposableStack covers these cases. It is a container that collects resources while your code runs and disposes all of them in reverse order with one call.
This chapter assumes you already know the using declaration, the Symbol.dispose protocol, reverse-order disposal, and SuppressedError from the earlier chapters. The examples run in Node.js 24 or later and in other runtimes that ship explicit resource management natively.
The Problem DisposableStack Solves
Each using declaration binds exactly one resource to one block. Two common situations don't fit that rule:
- Conditional resources. You can write
using x = cond ? open() : null, but this gets messy once several resources depend on several conditions. - A variable number of resources. A
usinginside a loop body disposes its resource at the end of each iteration. If you need all N resources open at the same time, a loop ofusingdeclarations cannot keep them alive.
A DisposableStack is itself disposable. You bind the stack with using, then register any number of resources on it. When the block exits, the stack disposes everything it holds, last registered first.
The API at a Glance
| Member | What it does | Returns |
|---|---|---|
| `use(value)` | Registers a disposable object. `null` and `undefined` are accepted and ignored. Throws `TypeError` if `value` has no `Symbol.dispose` method. | `value` |
| `adopt(value, onDispose)` | Registers any value plus a callback. At disposal, calls `onDispose(value)`. | `value` |
| `defer(onDispose)` | Registers a callback that takes no arguments. | `undefined` |
| `move()` | Transfers all registered resources to a new stack and marks this one as disposed. | new `DisposableStack` |
| `dispose()` | Disposes everything in reverse order. Calling it again does nothing. | `undefined` |
| `[Symbol.dispose]()` | Same as `dispose()`, so `using` works on the stack. | `undefined` |
| `disposed` | `true` once the stack has been disposed or moved. | boolean |
Calling use, adopt, defer, or move on a disposed stack throws a ReferenceError.
use, adopt, and defer Together
The three registration methods cover three kinds of cleanup:
usetakes objects that already follow the protocol.adoptwraps values that have their own cleanup function but noSymbol.dispose, such as timer IDs or handles from older libraries.defertakes arbitrary cleanup work, much like afinallyclause you can add while the code runs.
function resource(name) {
return {
name,
[Symbol.dispose]() {
console.log(`dispose ${name}`);
},
};
}
{
using stack = new DisposableStack();
const a = stack.use(resource("a"));
stack.use(null); // allowed, nothing is registered
stack.adopt(setTimeout(() => console.log("never runs"), 10_000), (id) => {
clearTimeout(id);
console.log("timer cleared");
});
stack.defer(() => console.log("deferred callback"));
console.log("work with", a.name);
}
// work with a
// deferred callback
// timer cleared
// dispose ause and adopt return the value you pass in, so registering a resource and assigning it fit on one line. defer returns undefined because it has no resource to hand back.
Conditional and Dynamic Resources
The most common use of a stack is a block whose set of resources depends on runtime data.
function resource(name) {
return {
name,
[Symbol.dispose]() {
console.log(`dispose ${name}`);
},
};
}
function processJob(job) {
using stack = new DisposableStack();
const log = stack.use(resource("log"));
const cache = job.useCache ? stack.use(resource("cache")) : null;
const inputs = job.inputs.map((name) => stack.use(resource(name)));
console.log(
`processing ${inputs.length} inputs`,
cache ? "with cache" : "without cache",
`logging to ${log.name}`
);
}
processJob({ useCache: true, inputs: ["in1", "in2"] });
// processing 2 inputs with cache logging to log
// dispose in2
// dispose in1
// dispose cache
// dispose logAll the inputs stay open until the function returns. If opening in2 threw, the stack would still dispose in1, cache, and log, because the using stack binding runs cleanup however the block exits.
Transferring Ownership with move
Sometimes resources must outlive the function that creates them. A constructor that opens several handles is the usual example. You want two different outcomes:
- If setup fails halfway, release whatever was already opened.
- If setup succeeds, keep everything open and give the caller one handle that cleans it all up later.
move() handles both. Do the setup under using stack. On success, call stack.move() as the last step. The resources go to a fresh stack that you store, and the original stack becomes empty and disposed, so its automatic cleanup at the end of the block does nothing.
function resource(name) {
return {
name,
[Symbol.dispose]() {
console.log(`dispose ${name}`);
},
};
}
class Pipeline {
#stack;
constructor(names, failAt = -1) {
using stack = new DisposableStack();
this.inputs = names.map((name, i) => {
if (i === failAt) throw new Error(`cannot open ${name}`);
return stack.use(resource(name));
});
this.#stack = stack.move(); // setup succeeded: keep the resources
}
[Symbol.dispose]() {
this.#stack.dispose();
}
}
try {
new Pipeline(["x", "y", "z"], 2);
} catch (e) {
console.log("failed:", e.message);
}
// dispose y
// dispose x
// failed: cannot open z
{
using p = new Pipeline(["x", "y"]);
console.log("pipeline ready");
}
// pipeline ready
// dispose y
// dispose xErrors During Disposal
A stack disposes its resources the same way a sequence of using declarations does. Every registered cleanup runs, even after an earlier one throws. Each new error wraps the error collected so far in a SuppressedError. Its error property holds the newer error, and its suppressed property holds the older one.
const stack = new DisposableStack();
stack.defer(() => {
throw new Error("first registered");
});
stack.defer(() => {
throw new Error("second registered");
});
stack.defer(() => console.log("still runs"));
try {
stack.dispose();
} catch (e) {
console.log(e instanceof SuppressedError); // true
console.log(e.error.message); // "first registered"
console.log(e.suppressed.message); // "second registered"
}
// still runs (logged first, before the catch)The newest-registered callback runs first and succeeds. "second registered" throws next. "first registered" throws last, so it becomes error, and the earlier failure is kept in suppressed. If the stack is bound with using and the block body also threw, the body's error sits deepest in the suppressed chain.
The disposed State
A stack can be disposed only once. After that, it refuses new resources, so nothing gets registered on a stack that will never clean it up.
const s = new DisposableStack();
console.log(s.disposed); // false
s.dispose();
console.log(s.disposed); // true
s.dispose(); // no-op, no error
try {
s.defer(() => {});
} catch (e) {
console.log(e instanceof ReferenceError); // true
}
const t = new DisposableStack();
const moved = t.move();
console.log(t.disposed, moved.disposed); // true falseCommon Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| `const stack = new DisposableStack()` with no `using` and no `dispose()` call | Nothing is ever cleaned up | Bind with `using`, or call `dispose()` in `finally` |
| Returning `stack.use(x)` from a function without `move()` | The caller receives a resource that is already disposed | `move()` the stack and return an owner that disposes it |
| Passing a plain object to `use` | `TypeError` at registration time | Use `adopt(value, cleanupFn)` instead |
| Passing a non-function to `adopt` or `defer` | `TypeError` | Pass a callable cleanup function |
| Registering after `move()` on the old stack | `ReferenceError` | Register on the stack returned by `move()` |
| Async cleanup inside `defer` | The promise is dropped and nobody awaits the cleanup | Use `AsyncDisposableStack` (next chapter) |
When to Choose a Stack Over Plain using
Use separate using declarations when the set of resources is fixed and known in advance. They read more clearly, and each name shows its own lifetime. Use a DisposableStack when:
- the number of resources depends on runtime data,
- resources are acquired conditionally,
- you need to wrap APIs that don't implement
Symbol.dispose, - a constructor or factory must hand all its resources to a single owner when setup succeeds.
Exercise
A stack registers, in order, use(A), defer(f), and adopt(t, clearTimeout). In what order does cleanup run when the stack is disposed, and what argument does each callback receive?
Show answer
Cleanup runs in reverse order of registration. First clearTimeout(t) runs, receiving the adopted value t. Then f() runs with no arguments. Last, A[Symbol.dispose]() runs with A as this.
Exercise
A function runs using stack = new DisposableStack(); const conn = stack.use(openConn()); return conn;. The caller reports that conn is closed as soon as it gets it. Why, and how do you fix it?
Show answer
The stack is disposed when the function's block exits, and that happens before the caller receives conn, so the connection is already closed. Fix it by calling const owned = stack.move(); before returning, then return an object that holds conn and whose [Symbol.dispose] calls owned.dispose(). The original stack is empty after move(), so disposing it at block exit does nothing.
Exercise
Three deferred callbacks are registered in the order X, Y, Z. X and Z throw, Y succeeds. What does dispose() throw?
Show answer
Z runs first and throws errZ. Y runs and succeeds. X runs and throws errX. dispose() throws a SuppressedError whose error is errX and whose suppressed is errZ.
Exercise
Write a function openMany(names) that opens one resource per name, closes all already-opened resources if any open fails, and on success returns a single disposable that closes them all.
Show answer
function openMany(names) { using stack = new DisposableStack(); const items = names.map((n) => stack.use(resource(n))); const owned = stack.move(); return { items, [Symbol.dispose]() { owned.dispose(); } }; } If resource(n) throws, move() is never reached, so the using binding disposes every item registered so far.