Sub topic 3
Making an Object Disposable
This chapter assumes you know ES classes, object literal methods, computed property keys, and how this binding works for regular functions and arrow functions. It also assumes you have read the previous chapter on Symbol.dispose and Symbol.asyncDispose. Here you will turn ordinary objects into resources that using and await using can clean up. The declarations themselves get full treatment in the next chapter. The focus here is the object side: what a disposable object has to provide, and what the runtime does with it.
The Disposable Protocol
A protocol in JavaScript is an agreement based on shape. The language never checks a class name or an instanceof relationship. It looks up a property with a well-known symbol key and calls it. Iteration works this way through Symbol.iterator, and resource management follows the same pattern.
| Protocol | Required member | Used by | Return value |
|---|---|---|---|
| Disposable | `[Symbol.dispose]()` | `using`, `await using`, `DisposableStack` | Ignored |
| Async disposable | `[Symbol.asyncDispose]()` | `await using`, `AsyncDisposableStack` | Awaited (a promise or any value) |
An object that has a callable [Symbol.dispose] property is a disposable. An object that has a callable [Symbol.asyncDispose] property is an async disposable. The method takes no arguments. The runtime calls it with the resource as this.
The Smallest Disposable: An Object Literal
The quickest way to make a disposable is a method with a computed key on an object literal.
const handle = {
name: "log-file",
[Symbol.dispose]() {
console.log(`closing ${this.name}`);
},
};
// The protocol is just a method. You can call it yourself:
handle[Symbol.dispose](); // closing log-file
{
using h = handle;
console.log("working with", h.name);
}
// working with log-file
// closing log-fileTwo points stand out. First, nothing about the object is special apart from the method, so you can call it by hand. That is useful in tests and in code that cannot use using yet. Second, the method sees the object as this because the runtime calls it on the resource value.
Class-Based Disposables
In most real code a resource is a class instance with state. When you define the method on the class, it lives on the prototype, so every instance is disposable without carrying its own copy.
class Lock {
#held = false;
#name;
constructor(name) {
this.#name = name;
}
static acquire(name) {
const lock = new Lock(name);
lock.#held = true;
console.log(`acquired ${name}`);
return lock;
}
get held() {
return this.#held;
}
[Symbol.dispose]() {
if (!this.#held) return; // idempotent: a second call does nothing
this.#held = false;
console.log(`released ${this.#name}`);
}
}
{
using lock = Lock.acquire("orders");
console.log("held?", lock.held);
}
// acquired orders
// held? true
// released ordersDisposal is inherited like any other method. A subclass can override [Symbol.dispose] and call super[Symbol.dispose]() to chain cleanup, which follows the usual rules for overriding methods.
Make dispose idempotent
An idempotent method gives the same result whether you call it once or many times. Disposal should be idempotent because several things can trigger it: a using block exit, a manual call in an error path, a DisposableStack that also owns the object, or a caller that does not know someone else already cleaned up. The #held check in Lock returns early on every call after the first. Without it, a double release could unlock a lock that another caller has since taken, or close a file descriptor number the OS has already given to a different file.
Track disposed state for the rest of the API
When a resource has been disposed, its other methods should fail loudly instead of acting on dead state. A common pattern is a private flag plus a guard:
class Buffer2 {
#data = [];
#disposed = false;
#assertOpen() {
if (this.#disposed) throw new ReferenceError("Buffer2 is disposed");
}
push(value) {
this.#assertOpen();
this.#data.push(value);
}
[Symbol.dispose]() {
if (this.#disposed) return;
this.#disposed = true;
this.#data.length = 0;
}
}
const buf = new Buffer2();
buf.push(1);
buf[Symbol.dispose]();
try {
buf.push(2);
} catch (e) {
console.log(e.message); // Buffer2 is disposed
}Which error type to throw is your choice. ReferenceError, TypeError, and a custom ObjectDisposedError are all common. Pick one and use it everywhere.
Async Disposables
When cleanup has to wait for I/O, such as flushing a write buffer or sending a close frame, implement [Symbol.asyncDispose] and return a promise. Writing it as an async method does that for you.
class Writer {
#pending = [];
#closed = false;
write(chunk) {
if (this.#closed) throw new TypeError("writer closed");
this.#pending.push(chunk);
}
async [Symbol.asyncDispose]() {
if (this.#closed) return;
this.#closed = true;
await new Promise((resolve) => setTimeout(resolve, 10)); // simulate flush
console.log(`flushed ${this.#pending.length} chunks`);
}
}
async function main() {
await using w = new Writer();
w.write("a");
w.write("b");
}
main().then(() => console.log("done"));
// flushed 2 chunks
// doneAn object can implement both methods. await using prefers [Symbol.asyncDispose]. Plain using only ever looks at [Symbol.dispose], so an object with only the async method cannot be used with using. Give a resource both methods only when a synchronous cleanup is genuinely complete, for example a best-effort close that skips flushing.
The sync fallback does not await
If an object has only [Symbol.dispose], await using still accepts it. The runtime wraps the sync method in an async adapter, so the declaration always has something to await. The adapter has a catch: it calls your sync method, throws away its return value, and resolves with undefined.
const sneaky = {
[Symbol.dispose]() {
// Returning a promise from a SYNC dispose method does not help.
return new Promise((resolve) =>
setTimeout(() => {
console.log("late cleanup");
resolve();
}, 20)
);
},
};
async function run() {
{
await using s = sneaky;
}
console.log("block exited");
}
run();
// block exited
// late cleanupWhat the Runtime Checks, and When
Some behavior here can surprise you. The runtime looks up the dispose method once, at the moment the declaration runs, and not when the block exits.
The flowchart has three practical consequences.
- Primitives are rejected immediately.
using x = 42throws aTypeErrorbefore the block body runs. Strings, numbers, and booleans cannot be resources, even if you add aSymbol.disposeto their prototypes. A later chapter coversnullandundefined, which are allowed and skipped. - A missing method fails early. Forgetting to add
[Symbol.dispose]raises aTypeErrorat theusingline, not at block exit. That is a good thing, because you find out before any work happens. - The method is captured. Replacing or deleting
[Symbol.dispose]after the declaration does not change what gets called.
const res = {
[Symbol.dispose]() {
console.log("original dispose");
},
};
{
using r = res;
r[Symbol.dispose] = () => console.log("replacement");
}
// original dispose
try {
using bad = { close() {} }; // no Symbol.dispose
} catch (e) {
console.log(e instanceof TypeError); // true
}The `this` Trap with Arrow Functions
Arrow functions do not get their own this. If you write the dispose method as an arrow function inside an object literal, this is whatever it was in the surrounding scope. That is usually undefined in a module or the global object in a script.
const broken = {
name: "socket",
[Symbol.dispose]: () => {
console.log(`closing ${this?.name}`); // `this` is not `broken`
},
};
broken[Symbol.dispose](); // closing undefinedUse method syntax ([Symbol.dispose]() {}) or a regular function expression. An arrow function is fine when it closes over variables instead of using this, which is how factories often write it:
function openTimer(ms) {
const id = setInterval(() => console.log("tick"), ms);
return {
id,
[Symbol.dispose]: () => clearInterval(id), // closure, not `this`
};
}
{
using t = openTimer(1000);
} // interval cleared immediately; nothing ticksAdapting Objects That Already Have close()
Many existing APIs already expose close(), release(), or end(). You can make them disposable by aliasing, which keeps one implementation and adds the protocol on top of it.
class LegacyConnection {
#open = true;
close() {
if (!this.#open) return;
this.#open = false;
console.log("legacy close");
}
}
// Alias on the prototype so every instance participates.
LegacyConnection.prototype[Symbol.dispose] = LegacyConnection.prototype.close;
{
using c = new LegacyConnection();
}
// legacy closeOnly alias a method when it takes no required arguments and is safe to call more than once. When those conditions do not hold, or you do not own the class, wrap the value instead. The DisposableStack chapter shows adopt and defer, which do this without touching any prototype.
Checklist for a Well-Behaved Disposable
| Property | Why it matters |
|---|---|
| Method syntax, not `this`-based arrow functions | The runtime calls the method with the resource as `this` |
| Idempotent | Disposal can be triggered from more than one place |
| Marks itself disposed | Later calls fail clearly instead of corrupting state |
| Async work lives in `Symbol.asyncDispose` | Promises returned from `Symbol.dispose` are never awaited |
| Throws only for real cleanup failures | Errors thrown during disposal are combined into `SuppressedError` chains |
Exercise
A Cache class defines [Symbol.dispose]() { return this.flushToDisk(); }, where flushToDisk is async. A developer writes await using c = new Cache(); and expects the flush to finish before the next line after the block. What actually happens, and how do you fix it?
Show answer
Cache has no Symbol.asyncDispose, so await using falls back to Symbol.dispose through an adapter that ignores the method's return value. The flush promise starts but is not awaited, so code after the block runs before the flush finishes, and a rejection goes unhandled. Fix it by renaming the method to async [Symbol.asyncDispose]() { await this.flushToDisk(); }. Add a separate synchronous [Symbol.dispose] only if you also need to support plain using.
Exercise
Predict the output of: const r = { [Symbol.dispose]() { console.log("A"); } }; { using x = r; delete r[Symbol.dispose]; console.log("B"); }
Show answer
It prints "B" and then "A". The dispose method is read and stored when the using declaration runs, so deleting the property afterward does not stop the original method from being called at block exit.
Exercise
Why does using n = 5; throw even if you first run Number.prototype[Symbol.dispose] = function () {};?
Show answer
using requires its value to be an object (or null/undefined). It checks the type before it looks for a dispose method. The number 5 is a primitive, so a TypeError is thrown at the declaration no matter what methods exist on Number.prototype.