Sub topic 2
Meet Symbol.dispose and Symbol.asyncDispose
Explicit resource management rests on two new well-known symbols, Symbol.dispose and Symbol.asyncDispose. The using and await using declarations look up these symbols on an object to find its cleanup method. Before you can write disposable objects or declare resources, you need to know what these symbols are, how they behave as property keys, and how to check whether a runtime has them.
This chapter assumes you know block scoping with let and const, try/finally, promises with async/await, class and object literal method syntax, and well-known symbols such as Symbol.iterator.
Well-known symbols as protocol hooks
A well-known symbol is a symbol value stored as a static property on the Symbol constructor. The language uses it as a fixed key to find behavior on objects. You have already met one. for...of does not look for a method called "iterator". It looks for a method stored under the key Symbol.iterator. Any object that has a function under that key can be iterated.
Symbol.dispose and Symbol.asyncDispose work the same way for cleanup:
| Symbol | Who calls it | Expected return value | Typical work |
|---|---|---|---|
| `Symbol.iterator` | `for...of`, spread, destructuring | An iterator object | Produce values |
| `Symbol.dispose` | `using`, `DisposableStack` | Ignored | Synchronous cleanup: release a lock, clear a timer |
| `Symbol.asyncDispose` | `await using`, `AsyncDisposableStack` | A promise, which is awaited | Asynchronous cleanup: flush and close a file, end a connection |
The language uses symbols instead of string names like "close" or "dispose" to avoid collisions. Many existing libraries already have methods called close(), end(), release(), or dispose(). Those methods vary: some take arguments, some return promises, and some do something other than cleanup. If using called any method named "dispose", it would call methods that were never written for it. A symbol key cannot clash with existing string-keyed methods, so only code that deliberately opts in takes part.
What the symbols look like
In a runtime that supports the feature, both symbols are ordinary symbol values with descriptive descriptions:
console.log(typeof Symbol.dispose); // "symbol"
console.log(typeof Symbol.asyncDispose); // "symbol"
console.log(Symbol.dispose.description); // "Symbol.dispose"
console.log(Symbol.asyncDispose.description); // "Symbol.asyncDispose"
console.log(String(Symbol.dispose)); // "Symbol(Symbol.dispose)"
// Well-known symbols are not in the global symbol registry
console.log(Symbol.keyFor(Symbol.dispose)); // undefined
console.log(Symbol.dispose === Symbol.for("Symbol.dispose")); // falseThe last two lines show a point people often get wrong. Symbol.for(key) returns a symbol from a global registry shared by the whole program. Well-known symbols do not live in that registry. You cannot rebuild Symbol.dispose with Symbol.for("Symbol.dispose"), and a symbol you create that way will not be recognized by using.
Well-known symbols are shared across realms. An iframe, a node:vm context, or a worker's own global has its own Symbol constructor, but Symbol.dispose has the same value in all of them within one agent. That is why an object created in one realm can be disposed by a using declaration in another.
The properties themselves are locked down:
console.log(Object.getOwnPropertyDescriptor(Symbol, "dispose"));
// { value: Symbol(Symbol.dispose), writable: false,
// enumerable: false, configurable: false }When the runtime provides the symbol natively, you cannot replace it. This is the same treatment Symbol.iterator gets.
Symbols as method keys
You attach a function under a symbol key with a computed property name, which is the key written in square brackets. This works in object literals and in class bodies:
const lock = {
held: true,
[Symbol.dispose]() {
this.held = false;
console.log("lock released");
},
};
class TempDir {
constructor(path) {
this.path = path;
}
async [Symbol.asyncDispose]() {
await new Promise((resolve) => setTimeout(resolve, 5));
console.log(`removed ${this.path}`);
}
}
lock[Symbol.dispose](); // "lock released"
await new TempDir("/tmp/x")[Symbol.asyncDispose](); // "removed /tmp/x"Run this as an ES module, for example a .mjs file in Node, because it uses top-level await. The example also shows that the dispose methods are ordinary methods. Nothing stops you from calling them directly. using simply calls them for you at the right moment.
Symbol-keyed properties are hidden from most string-based reflection:
const res = { name: "db", [Symbol.dispose]() {} };
console.log(Object.keys(res)); // ["name"]
console.log(JSON.stringify(res)); // {"name":"db"}
console.log(Object.getOwnPropertySymbols(res)); // [Symbol(Symbol.dispose)]
console.log(Reflect.ownKeys(res)); // ["name", Symbol(Symbol.dispose)]This is usually what you want. Logging, serialization, and for...in loops do not see the cleanup hook. Note that object spread ({ ...res }) and Object.assign do copy own enumerable symbol properties. A spread copy of a disposable object literal is disposable too, and it shares the same cleanup function.
How using and await using pick a method
The declarations covered in later chapters use the symbols in a specific way. A plain using looks only for Symbol.dispose. An await using looks first for Symbol.asyncDispose. If that method is missing, it falls back to Symbol.dispose, so a synchronous resource also works in an async block.
The fallback goes in one direction only. An object that has only Symbol.asyncDispose cannot be used with plain using, because synchronous code cannot wait for a promise. The lookup happens once, when the declaration runs. If you replace the method on the object later, the original function is still the one that gets called.
Built-in objects that already implement the symbols
You will not need to write every disposable yourself. In runtimes that ship the full feature, several built-ins already carry these methods:
| Object | Symbol | What disposal does |
|---|---|---|
| `DisposableStack.prototype` | `Symbol.dispose` | Disposes every registered resource in reverse order |
| `AsyncDisposableStack.prototype` | `Symbol.asyncDispose` | Same, awaiting each async cleanup |
| `Iterator.prototype` | `Symbol.dispose` | Calls `this.return()` if it exists |
| `AsyncIterator.prototype` | `Symbol.asyncDispose` | Calls and awaits `this.return()` if it exists |
Host environments add more. Node.js, for example, gives fs.promises FileHandle objects a Symbol.asyncDispose method that closes the handle. Check your runtime's documentation for the exact list, because it grows release by release.
The iterator entry means generator objects are disposable:
function* count() {
try {
yield 1;
yield 2;
} finally {
console.log("finally ran");
}
}
const it = count();
console.log(it.next().value); // 1
it[Symbol.dispose](); // calls it.return(), prints "finally ran"
console.log(it.next().done); // trueFeature detection and polyfilling
Support arrived in stages across engines, so production code often has to check for it first. Detect each symbol separately:
const hasDispose = typeof Symbol.dispose === "symbol";
const hasAsyncDispose = typeof Symbol.asyncDispose === "symbol";
console.log({ hasDispose, hasAsyncDispose });Having the symbols does not mean the runtime has the using syntax. These are separate parts of the feature. Some engines, and the TypeScript and Babel downlevel helpers, need the symbols to exist even though the syntax is compiled away. The usual shim creates them when they are missing:
Symbol.dispose ??= Symbol("Symbol.dispose");
Symbol.asyncDispose ??= Symbol("Symbol.asyncDispose");Run this once, before any module that defines or consumes disposables. In a native runtime the ??= sees an existing value and does nothing, so the shim is safe to leave in place. In an older runtime it creates a local stand-in symbol. That stand-in is not shared across realms, and code that loaded a different polyfill will have a different symbol. Use a single polyfill source, such as core-js, for the whole application.
To test whether a particular value is disposable, check the method rather than the type:
function isDisposable(value) {
return value != null && typeof value[Symbol.dispose] === "function";
}
function isAsyncDisposable(value) {
return value != null && typeof value[Symbol.asyncDispose] === "function";
}
console.log(isDisposable({ [Symbol.dispose]() {} })); // true
console.log(isDisposable({ dispose() {} })); // falseCommon errors
- Using a string key.
{ dispose() {} }or{ "Symbol.dispose"() {} }defines a string-keyed method thatusingignores. The key must be the symbol value, written[Symbol.dispose]. - Forgetting the brackets.
{ Symbol.dispose() {} }is a syntax error. Computed keys need square brackets. - Arrow functions and
this.[Symbol.dispose]: () => this.close()captures the surroundingthis, not the resource. Use method syntax, or close over the resource variable explicitly. - Not returning the promise. An async dispose method that starts work without returning or awaiting it lets
await usingmove on before cleanup finishes. Declare the methodasyncandawaitinside it. - Only providing the async method. If callers might use plain
usingorDisposableStack, also provideSymbol.dispose, or document that the resource is async-only. - Building a symbol with
Symbol.for. As shown above,Symbol.for("Symbol.dispose")is a different symbol from the well-known one.
Exercise
An object has only a method stored under Symbol.dispose. Which of these declarations accept it without a TypeError: using x = obj, await using x = obj? What changes if the object has only Symbol.asyncDispose?
Show answer
With only Symbol.dispose, both declarations accept it: using calls it directly, and await using falls back to it because Symbol.asyncDispose is missing. With only Symbol.asyncDispose, await using accepts it, but using throws a TypeError when the declaration runs, because plain using never looks at Symbol.asyncDispose.
Exercise
A teammate writes const key = Symbol.for("Symbol.dispose"); const res = { [key]() { console.log("bye"); } }; and wonders why using r = res; throws. Explain the problem and fix it.
Show answer
Symbol.for returns a symbol from the global registry, and well-known symbols are not in that registry, so key is a different symbol from Symbol.dispose. The object has no method under the real Symbol.dispose key, so using throws a TypeError. Fix it by using the well-known symbol directly: const res = { [Symbol.dispose]() { console.log("bye"); } };.
Exercise
Why does Object.keys(res) not list the dispose method, and what would you call to see it?
Show answer
Object.keys returns only own enumerable string-keyed properties, and the dispose method is keyed by a symbol. Use Object.getOwnPropertySymbols(res) or Reflect.ownKeys(res) to see symbol keys.