Sub topic 13
Designing Your Own Disposable Resources
This chapter assumes you already know how using, await using, and DisposableStack behave. It also assumes you are comfortable with private class fields (#field), getters, and EventTarget. Earlier chapters covered how the language consumes disposables. This one covers how to build them so that callers can't misuse them easily, whether or not those callers write using.
A disposable object only has to provide a [Symbol.dispose] or [Symbol.asyncDispose] method. That bar is low, so a method that technically works can still be badly designed. The patterns below cover what goes wrong in practice: double disposal, use after disposal, partial construction, async work hidden in sync cleanup, and lost this bindings.
The Lifecycle of a Well-Behaved Resource
A disposable resource has two states that matter: open and disposed. Your design has to say what each operation does in each state.
Two rules come out of this diagram:
- Disposal is idempotent. Calling it twice does the same thing as calling it once. Resources often end up disposed by more than one path: a
usingblock, an explicitclose(), and a parentDisposableStack. A second call must not double-free, double-log, or throw. - Use after disposal fails loudly. If an operation on a disposed resource quietly returns stale data, the bug shows up later and somewhere else. Throw right away with a message that names the resource.
A Baseline Synchronous Resource
This class applies both rules. It keeps its state in a private field, exposes a read-only disposed getter so callers can check it, and offers a close() alias for code that doesn't use using.
class Handle {
#name;
#disposed = false;
constructor(name) {
this.#name = name;
console.log(`open ${name}`);
}
get disposed() {
return this.#disposed;
}
read() {
if (this.#disposed) {
throw new ReferenceError(`Handle "${this.#name}" is already disposed`);
}
return `data from ${this.#name}`;
}
close() {
this[Symbol.dispose]();
}
[Symbol.dispose]() {
if (this.#disposed) return; // idempotent
this.#disposed = true; // set state first
console.log(`close ${this.#name}`);
}
}
let leaked;
{
using h = new Handle("config");
console.log(h.read());
h.close(); // explicit early close
leaked = h;
} // using calls dispose again: no-op
console.log(leaked.disposed); // true
try {
leaked.read();
} catch (e) {
console.log(e.message); // Handle "config" is already disposed
}Output:
open config
data from config
close config
true
Handle "config" is already disposedclose config prints only once, even though disposal ran twice. The method also sets #disposed = true before it does the cleanup work. If the cleanup throws partway through, a retry won't run the half-finished cleanup again, and any re-entrant call made during cleanup hits the guard.
Returning Disposables from Functions
A resource doesn't have to be a class. Any function that registers something can return a small disposable that undoes the registration. Event subscriptions are the classic case, because forgetting removeEventListener is a common leak.
function listen(target, type, handler) {
target.addEventListener(type, handler);
let active = true;
return {
[Symbol.dispose]() {
if (!active) return;
active = false;
target.removeEventListener(type, handler);
},
};
}
const bus = new EventTarget();
{
using subscription = listen(bus, "ping", () => console.log("got ping"));
bus.dispatchEvent(new Event("ping")); // got ping
}
bus.dispatchEvent(new Event("ping")); // nothing: listener was removedThis pattern also works for locks, timers, temporary global overrides, and feature flags. In each case the function performs an action and returns its inverse. The scope of the using declaration then decides how long the action lasts.
Acquiring Several Resources Safely
A resource that owns other resources has a construction problem. Suppose it opens a source and then a sink, and opening the sink throws. The source is already open, but the constructor never returned, so nobody holds a reference that could dispose it.
The fix is to acquire children inside a static factory, register them on a DisposableStack declared with using, and call move() only after every acquisition has succeeded.
class Part {
#name;
#disposed = false;
constructor(name, fail = false) {
if (fail) throw new Error(`cannot open ${name}`);
this.#name = name;
console.log(`open ${name}`);
}
[Symbol.dispose]() {
if (this.#disposed) return;
this.#disposed = true;
console.log(`close ${this.#name}`);
}
}
class Pipeline {
#stack;
#source;
#sink;
constructor(stack, source, sink) {
this.#stack = stack;
this.#source = source;
this.#sink = sink;
}
static create({ failSink = false } = {}) {
using stack = new DisposableStack();
const source = stack.use(new Part("source"));
const sink = stack.use(new Part("sink", failSink));
return new Pipeline(stack.move(), source, sink);
}
[Symbol.dispose]() {
this.#stack.dispose(); // DisposableStack.dispose is already idempotent
}
}
{
using p = Pipeline.create();
console.log("pipeline running");
}
try {
Pipeline.create({ failSink: true });
} catch (e) {
console.log(e.message);
}Output:
open source
open sink
pipeline running
close sink
close source
open source
close source
cannot open sinkIn the failing call, stack disposes source as the factory exits by throwing. In the successful call, move() empties the local stack, so its own disposal does nothing, and the new stack's ownership passes to the Pipeline instance. The children are disposed in reverse order of acquisition, as they would be with separate using declarations.
Constructors can't do this safely by themselves. A constructor can't declare a using stack and hand it to the instance without the same move() dance, and many teams prefer to keep constructors free of I/O anyway. A static create or open method is the usual convention.
Choosing Between Sync and Async Disposal
Pick the protocol based on what the cleanup actually does.
| Cleanup work | Implement | Caller writes |
|---|---|---|
| Pure in-memory work: clear a timer, remove a listener, release a lock flag | `[Symbol.dispose]` | `using` or `await using` |
| Needs I/O or a promise: flush a buffer, close a socket, commit a transaction | `[Symbol.asyncDispose]` | `await using` |
| Async close exists, plus a best-effort sync fallback | Both, documenting the difference | Either |
await using falls back to [Symbol.dispose] when no async method exists. That means a sync-only resource works in both kinds of declaration, and you don't need to add an async version "for compatibility".
The mistake to avoid is starting async work inside [Symbol.dispose]. Under using, the return value of the dispose method is ignored. A returned promise is never awaited, the block moves on before the cleanup finishes, and a rejection becomes an unhandled rejection rather than an error in the block.
class BufferedWriter {
#buffer = [];
#closed = false;
write(line) {
if (this.#closed) throw new ReferenceError("writer is closed");
this.#buffer.push(line);
}
async flush() {
const lines = this.#buffer.splice(0);
await new Promise((resolve) => setTimeout(resolve, 10)); // simulated I/O
for (const line of lines) console.log(`wrote: ${line}`);
}
async [Symbol.asyncDispose]() {
if (this.#closed) return;
this.#closed = true; // block new writes before awaiting
await this.flush();
}
}
async function main() {
{
await using out = new BufferedWriter();
out.write("alpha");
out.write("beta");
} // flush completes before the next line runs
console.log("after block");
}
main();Output:
wrote: alpha
wrote: beta
after blockThe writer sets #closed before the first await. Without that ordering, code running during the flush could add lines that would never be written.
The `this` Binding Gotcha
using and stack.use() call the dispose method with the resource as this. Detaching the method breaks that:
class Counter {
count = 0;
[Symbol.dispose]() {
this.count++;
}
}
const c = new Counter();
const stack = new DisposableStack();
// Wrong: the method is detached, so `this` is undefined when it runs.
// stack.defer(c[Symbol.dispose]);
// Right: let the stack call it on the object, or bind it.
stack.use(c);
stack.dispose();
console.log(c.count); // 1If the commented line ran, stack.dispose() would throw a TypeError when the method reads this.count. Design your methods so they don't depend on a detached this: use arrow functions in object literals that close over state, as listen does above. Or document that callers should pass the object to use(), not the method to defer().
Throwing from Disposal
Cleanup should almost never throw. When it does, the error either replaces a successful result or gets wrapped in a SuppressedError together with the block's own error, as covered in the error-handling chapter. Some guidelines:
- Throw only when the caller has to know. A failed transaction commit counts. A second
close()on an already-closed socket doesn't. - Swallow or log errors that are expected during teardown, such as "connection already reset".
- Mark the resource as disposed even when cleanup fails, so that retries and parent stacks don't run it again.
Design Checklist
| Concern | Recommended choice |
|---|---|
| Double disposal | Guard flag, set before the cleanup work |
| Use after disposal | Throw immediately with the resource's name |
| Multi-step acquisition | Static factory with `using stack` and `move()` |
| Non-`using` callers | Named `close()` that delegates to the dispose method |
| Async cleanup | `[Symbol.asyncDispose]` only, never a promise from sync dispose |
| Inspecting state | Read-only `disposed` getter |
| Expected teardown errors | Log or ignore, don't throw |
Exercise
A TempDir class creates a directory in its constructor and removes it in [Symbol.dispose]. A user writes using dir = new TempDir(); dir.close();, and the program crashes with "ENOENT: no such file or directory" at the end of the block. What design rule was missed, and what minimal change fixes it?
Show answer
Disposal isn't idempotent. close() removed the directory, and the using declaration then called [Symbol.dispose] again, which tried to remove a directory that no longer existed. Add a private #disposed flag. Have [Symbol.dispose] return early when the flag is already set, and set it to true before deleting, with close() delegating to [Symbol.dispose].
Exercise
A cache class implements [Symbol.dispose]() { return this.saveToDisk(); }, where saveToDisk is async. Users report that data saved just before the end of a using block is sometimes missing. Explain why, and say how the class should be changed.
Show answer
Under using, the return value of [Symbol.dispose] is ignored, so the promise from saveToDisk() is never awaited. Code after the block, including process exit, can run before the save finishes, and a failed save becomes an unhandled rejection. Implement async [Symbol.asyncDispose]() { if (this.#closed) return; this.#closed = true; await this.saveToDisk(); } and tell callers to use await using. If you keep a sync [Symbol.dispose] at all, it should do only synchronous work.
Exercise
In the Pipeline.create factory, what would happen if the final line were return new Pipeline(stack, source, sink); without calling move()?
Show answer
The using stack declaration would still dispose the stack when the factory returns, so sink and source would close before the caller ever got the pipeline. The returned object would hold a stack that is already disposed and children that are already closed. move() transfers the registered resources to a new stack and leaves the local one empty, so the local disposal does nothing.