Sub topic 3
Making an Object Disposable
This chapter assumes you know ES classes, object literal methods, Promises with async/await, and well-known symbols such as Symbol.iterator. It covers the contract an object has to meet before using or await using can clean it up. The declarations themselves are covered in the next chapters. Here the focus is on the resource side.
The disposable protocol
An object is disposable if it has a method stored under the Symbol.dispose key. An object is async disposable if it has a method under Symbol.asyncDispose that returns a promise. That is the whole protocol. You don't extend a base class, implement an interface, or register anything.
| Kind | Key | Return value | Consumed by |
|---|---|---|---|
| Disposable | `Symbol.dispose` | ignored | `using`, `await using` |
| Async disposable | `Symbol.asyncDispose` | a promise, which is awaited | `await using` |
Both an object literal and a class can meet this contract:
// Object literal
const tempFile = {
path: "/tmp/report.txt",
[Symbol.dispose]() {
console.log(`deleted ${this.path}`);
},
};
// Class
class Lock {
#held = true;
release() {
if (!this.#held) return;
this.#held = false;
console.log("lock released");
}
[Symbol.dispose]() {
this.release();
}
}
// The protocol is just a method call; using will make it for you.
tempFile[Symbol.dispose](); // deleted /tmp/report.txt
const lock = new Lock();
lock[Symbol.dispose](); // lock released
lock[Symbol.dispose](); // no output: already releasedDelegating to a named method such as release() is a common pattern. Callers who aren't using using can still clean up explicitly, and the symbol method becomes a thin adapter.
Async disposal
When cleanup involves I/O, such as flushing a buffer or closing a socket, implement Symbol.asyncDispose as an async method:
class LogWriter {
#buffer = [];
#closed = false;
write(line) {
if (this.#closed) throw new Error("writer closed");
this.#buffer.push(line);
}
async [Symbol.asyncDispose]() {
if (this.#closed) return;
this.#closed = true;
await new Promise((r) => setTimeout(r, 10)); // simulate flush
console.log(`flushed ${this.#buffer.length} lines`);
}
}
const log = new LogWriter();
log.write("start");
log.write("end");
await log[Symbol.asyncDispose](); // flushed 2 linesRun this as an ES module (a .mjs file) so that top-level await works.
An object can implement both methods. await using prefers Symbol.asyncDispose. If that method is missing, await using falls back to Symbol.dispose. Plain using only ever looks at Symbol.dispose.
Common errors
- Using a string key. A method named
disposeor"Symbol.dispose"doesn't count. The key must be the symbol itself, written in computed-property form:[Symbol.dispose]. - Returning a promise from
Symbol.dispose. Synchronoususingdiscards the return value, so async work started there runs unobserved, and its rejections go unhandled. Put async cleanup inSymbol.asyncDispose. - Arrow functions that need
this. If you write[Symbol.dispose]: () => this.close()in an object literal,thisrefers to the surrounding scope, not the object. Use method syntax, or close over a variable on purpose. - Non-idempotent cleanup. Cleanup can run more than once, for example when someone calls
release()andusingalso disposes the object. A guard flag like#heldor#closedmakes repeated calls harmless. - Throwing for "already closed". Prefer a silent return. An error thrown during disposal gets wrapped with the original error, which makes failures harder to read. A later chapter covers this.
Exercise
An object has [Symbol.dispose]() { return fetch("/logout"); }. What happens to the request's outcome when the object is used with using, and how should you fix it?
Show answer
using calls the method and discards the returned promise. The request starts, but nothing awaits it, and a rejection becomes an unhandled rejection. To fix it, implement async [Symbol.asyncDispose]() { await fetch("/logout"); } and declare the resource with await using.
Exercise
Why does the Lock class check #held before releasing?
Show answer
To make disposal idempotent. Then a manual release() call followed by automatic disposal, or any other repeated call, does nothing the second time instead of releasing twice or throwing.