Sub topic 2
Meet Symbol.dispose and Symbol.asyncDispose
This chapter assumes you know well-known symbols such as Symbol.iterator, object literal methods, and Promises with async/await. The previous chapter showed how try/finally cleanup breaks down as code grows. Explicit resource management fixes that by giving cleanup a standard name, and that name is a symbol.
Two new well-known symbols
A well-known symbol is a built-in symbol that the language itself looks for on your objects. Symbol.iterator is the familiar one. for...of calls the method stored under that key. Explicit resource management adds two more:
| Symbol | Called by | Expected return |
|---|---|---|
| `Symbol.dispose` | `using`, `DisposableStack` | Ignored |
| `Symbol.asyncDispose` | `await using`, `AsyncDisposableStack` | A Promise, which is awaited |
Each symbol works as a protocol key. If an object has a method under that key, the language knows how to clean it up. You never call the method by name in normal use. The runtime calls it for you when a scope ends.
console.log(typeof Symbol.dispose); // "symbol"
console.log(Symbol.dispose.description); // "Symbol.dispose"
console.log(Symbol.asyncDispose.description); // "Symbol.asyncDispose"
// Well-known symbols are not in the global registry
console.log(Symbol.keyFor(Symbol.dispose)); // undefined
console.log(Symbol.dispose === Symbol.for("Symbol.dispose")); // falseThe last line matters. Symbol.for("Symbol.dispose") is a different symbol. A method stored under that key will never be called during disposal.
Why symbols instead of a `close()` method
Existing APIs already use names like close, end, release, destroy, and return. The language could not pick one string name without colliding with methods that already mean something else. A symbol key cannot collide with any string property, so libraries can add disposal support without changing their existing public methods.
const file = {
close() {
console.log("legacy close");
},
[Symbol.dispose]() {
this.close();
},
};
file[Symbol.dispose](); // "legacy close"Calling the method by hand like this is legal. It is just an ordinary method call. The next chapters let using make that call automatically.
Sync versus async: which symbol to implement
Use Symbol.dispose when cleanup finishes immediately, for example clearing a timer, releasing a lock flag, or closing a synchronous file handle. Use Symbol.asyncDispose when cleanup has to wait for something, such as flushing a stream or sending a "goodbye" over a network connection.
const syncThing = {
[Symbol.dispose]() {
console.log("sync cleanup");
return "this value is ignored";
},
};
const asyncThing = {
async [Symbol.asyncDispose]() {
await new Promise((resolve) => setTimeout(resolve, 10));
console.log("async cleanup");
},
};
syncThing[Symbol.dispose]();
asyncThing[Symbol.asyncDispose]().then(() => console.log("awaited"));Detecting support
Older runtimes do not define these symbols. If one is missing, the property reads as undefined, and a computed key [Symbol.dispose] silently becomes the string "undefined". That is a common early mistake. Check for the symbol before you rely on it:
const hasDispose = typeof Symbol.dispose === "symbol";
const hasAsyncDispose = typeof Symbol.asyncDispose === "symbol";
console.log({ hasDispose, hasAsyncDispose });TypeScript's documentation suggests a minimal shim for environments that lack the symbols:
Symbol.dispose ??= Symbol("Symbol.dispose");
Symbol.asyncDispose ??= Symbol("Symbol.asyncDispose");Exercise
An object defines [Symbol.for("Symbol.dispose")]() { ... }. Will a using declaration call this method? Why or why not?
Show answer
No. Symbol.for creates or fetches a symbol from the global registry, and that symbol is distinct from the well-known Symbol.dispose. The using declaration looks only for Symbol.dispose, so it finds no disposal method and throws a TypeError.
Exercise
You need cleanup that flushes buffered data over the network before it finishes. Which symbol should you implement, and what should the method return?
Show answer
Implement Symbol.asyncDispose, and return a Promise that settles once the flush completes. An async method does this automatically. The await using declaration awaits that Promise before it moves on.