[FEE-10002] Explicit Resource Management — using & await using
INFO
Every unclosed database connection, every file handle left dangling after an exception, traces back to cleanup code that depended on a developer remembering to write it. using makes that cleanup unconditional and co-located with the resource allocation.
Web Platform Proposals
This proposal reached TC39 Stage 4 in May 2025 and now sits in TC39's finished-proposals set, so the API surface below is final. It ships natively in Chromium 134 / V8 v13.8 and Node.js 24+ (V8 13.6+), and is supported in TypeScript 5.2+, with Babel and a core-js polyfill available for older runtimes. See Runtime & Version Reference below for the full compatibility table, and check the TC39 proposal repository for any status updates.
Context
Resource management in JavaScript has historically relied on try/finally blocks. The pattern is well-known but deeply error-prone. Every time a developer manually writes cleanup code, they are one mistake away from a resource leak.
The four failure modes of try/finally
1. Forgetting the finally block entirely. When developers focus on the happy path, finally is often an afterthought. In code review or under deadline pressure, it gets skipped.
async function handleRequest(req) {
const db = await openConnection();
const result = await db.query(req.params.id); // throws on bad id
await db.close(); // never reached if query throws
return result;
}The connection leaks on every error. The problem may not surface until the connection pool is exhausted in production.
2. Forgetting to await in an async finally block. This is a subtle variant that TypeScript does not catch by default.
async function handleRequest(req) {
const db = await openConnection();
try {
return await db.query(req.params.id);
} finally {
db.close(); // missing await — close() runs but errors are silently dropped
}
}The finally block returns a floating Promise. The connection may not be closed before the next request arrives.
3. Errors thrown during cleanup silently swallow the original error. If both the body and the finally block throw, the finally error wins and the original error is lost forever.
async function doWork() {
const db = await openConnection();
try {
throw new Error('query failed'); // original error
} finally {
throw new Error('close failed'); // this replaces the original
// "query failed" is gone — you will never see it in your logs
}
}4. Multiple resources require nested try/finally blocks. Each additional resource adds a level of nesting and another opportunity for mistakes.
async function handleRequest(req) {
const db = await openConnection();
try {
const file = await openFile(req.params.path);
try {
return await processFileWithDb(file, db);
} finally {
await file.close();
}
} finally {
await db.close();
}
}The pyramid grows with every resource. The cleanup logic is separated from the allocation logic by an arbitrary distance. The resource lifetime is not visually clear.
A combined example: database and file handle
A request handler for a Node.js API needs a database connection to look up a user record, then a file handle to write an audit log entry. The developer adds a finally block for the database connection but forgets the file handle:
// BROKEN: file handle leaks on error
async function auditHandler(req, res) {
const db = await Database.connect(process.env.DB_URL);
try {
const user = await db.findUser(req.body.userId);
const logFile = await fs.open('./audit.log', 'a');
// If this line throws, logFile is never closed
await logFile.appendFile(`[${new Date().toISOString()}] ${user.name} accessed\n`);
await logFile.close();
res.json({ ok: true });
} finally {
await db.close(); // db is always cleaned up
// logFile.close() was forgotten here
}
}The file handle leaks on any error thrown by appendFile. In high-traffic conditions this exhausts the OS file descriptor limit.
using and await using fix this structurally: cleanup is declared at the point of allocation, so it cannot be left out of a finally block that was never written. The two keywords map to two disposal methods. using calls a resource's synchronous [Symbol.dispose](); await using calls its asynchronous [Symbol.asyncDispose]() and awaits the result. Both db and logFile below use the async form, because closing a database connection and a file handle are both asynchronous operations in Node.js:
// FIXED: both resources are always cleaned up
async function auditHandler(req, res) {
await using db = await Database.connect(process.env.DB_URL);
// db[Symbol.asyncDispose]() is called when this scope exits, no matter what
const user = await db.findUser(req.body.userId);
await using logFile = await fs.open('./audit.log', 'a');
// logFile[Symbol.asyncDispose]() is called when this scope exits
await logFile.appendFile(`[${new Date().toISOString()}] ${user.name} accessed\n`);
res.json({ ok: true });
// Both db and logFile are disposed here, in reverse declaration order
}The file handle now closes on every exit path, including the throw that previously leaked it.
Visual
Comparison: using vs try/finally control flow
| Scenario | try/finally | using |
|---|---|---|
| Cleanup on normal exit | Yes (with finally) | Always |
| Cleanup on throw | Yes (with finally) | Always |
| Forgetting cleanup | Possible | Impossible — cleanup is on the class |
| Both body and dispose throw | Original error lost | Both preserved in SuppressedError |
| Multiple resources | Nested blocks | Linear declarations |
| Cleanup location | Call site | Class definition |
Example
1. Basic using with a database connection
class DatabaseConnection {
#pool;
#client;
constructor(client, pool) {
this.#client = client;
this.#pool = pool;
}
async query(sql, params = []) {
return this.#client.query(sql, params);
}
// Synchronous dispose: return client to pool immediately
[Symbol.dispose]() {
this.#pool.release(this.#client);
}
}
class DatabasePool {
// ... pool implementation
async connect() {
const client = await this.#acquireClient();
return new DatabaseConnection(client, this);
}
release(client) {
this.#clients.push(client);
}
}
// Usage — connection is always returned to pool, even on throw
async function getUserById(pool, userId) {
using conn = await pool.connect();
const rows = await conn.query('SELECT * FROM users WHERE id = $1', [userId]);
return rows[0] ?? null;
// conn[Symbol.dispose]() called here — client returned to pool
}2. await using with an async file handle
import { open } from 'node:fs/promises';
class AsyncFileHandle {
#handle;
constructor(handle) {
this.#handle = handle;
}
async read() {
return this.#handle.readFile({ encoding: 'utf8' });
}
async write(data) {
return this.#handle.writeFile(data, { encoding: 'utf8' });
}
async [Symbol.asyncDispose]() {
await this.#handle.close();
// File descriptor released — safe to call multiple times if needed
}
}
async function appendAuditLog(userId, action) {
await using fh = new AsyncFileHandle(await open('./audit.log', 'a'));
await fh.write(`${new Date().toISOString()} user=${userId} action=${action}\n`);
// fh[Symbol.asyncDispose]() called here — file handle closed
}3. DisposableStack composing multiple resources
// Polyfill: import 'core-js/proposals/explicit-resource-management' (side-effect)
// Native in Node.js 24+ and Chrome 134+
async function processTransaction(db, items) {
await using stack = new AsyncDisposableStack();
// Acquire a transaction — wrap it so the stack can dispose it
const tx = await db.beginTransaction();
stack.defer(async () => {
if (!tx.committed) {
await tx.rollback(); // always rollback uncommitted transactions
}
});
// Acquire a lock for each item
for (const item of items) {
const lock = await acquireRowLock(item.id);
// .adopt() handles resources without [Symbol.asyncDispose]
stack.adopt(lock, async (l) => await l.release());
}
// Process everything
for (const item of items) {
await tx.update('items', { processed: true }, { id: item.id });
}
await tx.commit();
// stack disposes in reverse order:
// 1. item locks released (in reverse acquisition order)
// 2. rollback guard runs (no-op because tx.committed is true)
}Best Practices
Engineers MUST implement [Symbol.dispose]() on any class that manages a resource. This includes database connections, file handles, locks, subscriptions, event listeners, and timers: if a class acquires something that must be released, it must expose a disposal interface.
class DatabaseConnection {
#conn;
constructor(conn) {
this.#conn = conn;
}
async query(sql) {
return this.#conn.execute(sql);
}
// Sync dispose: for classes where cleanup is synchronous
[Symbol.dispose]() {
this.#conn.closeSync();
}
// Async dispose: for classes where cleanup is asynchronous
async [Symbol.asyncDispose]() {
await this.#conn.close();
}
}Engineers SHOULD prefer using over try/finally for all resource cleanup. The using keyword makes cleanup unconditional: it runs on both normal exit and on throw. Cleanup logic also lives on the class next to the resource it manages, instead of being duplicated at every call site.
Use DisposableStack (demonstrated in Example 3 above) when managing a variable number of resources, such as dynamically acquired locks, a batch of connections, or resources created inside a loop.
async function processItems(items) {
await using stack = new AsyncDisposableStack();
for (const item of items) {
// .use() registers a disposable; stack takes ownership
const lock = stack.use(await acquireLock(item.id));
await processItem(item, lock);
}
// All locks are released in reverse order when stack exits scope
}When both sync and async disposal are needed, implement both [Symbol.dispose] and [Symbol.asyncDispose]. This allows the class to be used with both using (sync contexts) and await using (async contexts).
Do not throw from [Symbol.dispose]. If cleanup fails, log and suppress the error, or throw a SuppressedError: a built-in error type introduced by this proposal that carries the original error as .suppressed and the dispose error as .error, so neither is lost (Design Thinking below has the full semantics). A dispose that throws without being wrapped this way will replace the original error in the caller's stack, making debugging harder.
[Symbol.dispose]() {
try {
this.#conn.closeSync();
} catch (err) {
// Log but do not re-throw
console.error('Connection close failed:', err);
}
}Design Thinking
RAII: a decades-old pattern JavaScript was missing
RAII (Resource Acquisition Is Initialization) is a C++ design principle introduced by Bjarne Stroustrup in the 1980s. The core idea: tie resource lifetime to object scope. When an object goes out of scope, its destructor runs unconditionally, even while an exception is propagating.
JavaScript has had closures, Promises, and async/await, but no language-level equivalent of RAII. C++, C#, Python, and Java all had scope-bound cleanup; JavaScript had none, so developers tracked and released resources by hand.
How other languages solved this
JavaScript is one of the last major languages to add explicit resource management syntax:
| Language | Syntax | Interface |
|---|---|---|
| C++ | Destructor (~T()) | Runs when scope exits |
| Python | with statement | __enter__ / __exit__ |
| C# | using statement | IDisposable.Dispose() |
| Java | try-with-resources | AutoCloseable.close() |
| Swift | defer statement | Arbitrary statement |
| Kotlin | .use {} extension | Closeable.close() |
| Go | defer statement | Arbitrary statement |
| JavaScript | using / await using | [Symbol.dispose]() / [Symbol.asyncDispose]() |
The JavaScript design is closest to C#: a keyword invokes a well-known interface method at scope exit. JavaScript adds a separate async variant, await using, to accommodate its pervasive use of asynchronous APIs.
React's useEffect cleanup is the same concept
React developers already think in terms of "setup and cleanup":
useEffect(() => {
const subscription = eventBus.subscribe(handler);
return () => {
subscription.unsubscribe(); // cleanup function
};
}, []);The return () => {} in useEffect is RAII in the component lifecycle. The Explicit Resource Management proposal brings the same concept to plain JavaScript scope, without requiring React or any framework. The cleanup function becomes [Symbol.dispose](), and the scope boundary becomes the using declaration.
SuppressedError: preserving both errors
Before this proposal, if both the body and a cleanup routine threw, one error was silently lost:
// The original error "body threw" is replaced by "cleanup threw"
// You will never see "body threw" in your logsThe proposal introduces SuppressedError to preserve both:
// SuppressedError structure:
// err.message — "An error was suppressed during disposal"
// err.error — the error thrown by [Symbol.dispose]() (the suppressor)
// err.suppressed — the original error thrown by the body (the suppressed)When using catches both a body error and a dispose error, it wraps them in a SuppressedError and throws that, giving the catch block access to both the original problem and the cleanup failure.
Deep Dive
How using interacts with try/catch/finally
using registers a dispose action that runs when the lexical scope exits. That exit follows a precise order with respect to try/catch/finally:
- The
finallyblock runs first. - The
usingdispose actions run afterfinally, in reverse declaration order.
function example() {
using a = new ResourceA();
using b = new ResourceB();
try {
throw new Error('body error');
} catch (err) {
console.log('catch:', err.message);
} finally {
console.log('finally');
// b[Symbol.dispose]() and a[Symbol.dispose]() have NOT run yet
}
// b[Symbol.dispose]() runs here (last declared, first disposed)
// a[Symbol.dispose]() runs here (first declared, last disposed)
}
// Output:
// catch: body error
// finally
// (dispose b)
// (dispose a)This ordering is intentional: the finally block may still reference the resources (for logging, flushing, etc.), so disposal happens after finally completes. Note: this ordering applies when using is declared in the enclosing function scope, outside the try block. If using is declared inside a try block, its disposal fires when that try-block scope exits, before finally runs.
SuppressedError semantics
SuppressedError is a new built-in error type introduced by this proposal. It extends Error.
try {
using resource = new FailingResource();
throw new Error('body error');
} catch (err) {
if (err instanceof SuppressedError) {
console.log('Original error:', err.suppressed.message); // "body error"
console.log('Cleanup error:', err.error.message); // from dispose
}
}The naming is intentional but can be confusing at first:
err.suppressedholds the original body error (the one that was suppressed).err.errorholds the dispose error (the one that caused the suppression).
Think of it as: the dispose error is the "active" error (err.error), and the body error was "suppressed" by it (err.suppressed).
DisposableStack methods
DisposableStack (and its async counterpart AsyncDisposableStack) provide a stack of disposables that are all released when the stack itself is disposed. This is the right tool for dynamic resource management.
function createBatch(items) {
const stack = new DisposableStack();
for (const item of items) {
// .use(resource) — registers a Disposable; returns the resource
const conn = stack.use(openConnection(item));
// .adopt(value, fn) — registers a non-Disposable with a callback
stack.adopt(conn.socket, (socket) => socket.destroy());
// .defer(fn) — registers an arbitrary cleanup callback
stack.defer(() => console.log(`closed connection for ${item}`));
}
return stack; // caller is responsible for disposing
}
{
using batch = createBatch(['a', 'b', 'c']);
// use batch...
} // all connections closed, sockets destroyed, log messages printedThe four methods on DisposableStack:
| Method | What it accepts | When to use |
|---|---|---|
.use(disposable) | Any object with [Symbol.dispose]() | Transferring ownership of a disposable |
.adopt(value, fn) | Any value + cleanup callback | Non-disposable resources (raw sockets, native handles) |
.defer(fn) | A zero-argument function | Arbitrary side effects at cleanup time |
.move() | Nothing | Transfer ownership: returns a new stack; old stack is empty |
TypeScript support
TypeScript 5.2 added using and await using as first-class keywords. The relevant types are in the lib definitions:
// TypeScript built-in interfaces (no import needed)
interface Disposable {
[Symbol.dispose](): void;
}
interface AsyncDisposable {
[Symbol.asyncDispose](): Promise<void>;
}
// TypeScript infers the type of `conn` from the right-hand side
using conn = new DatabaseConnection(url);
// ^^^^ TypeScript checks that DatabaseConnection implements DisposableTypeScript will emit a compile error if you use using with a type that does not implement [Symbol.dispose](). This static check eliminates an entire class of runtime errors.
To use using in a TypeScript project targeting older environments, add "lib": ["ES2022", "ESNext.Disposable"] (or "ESNext") to your tsconfig.json.
Runtime & Version Reference
Explicit Resource Management reached TC39 Stage 4 in May 2025 and now sits in the finished-proposals list; the TC39 proposals table lists an expected publication year of ES2027. The table below reflects verified support as of July 2026.
| Runtime / tool | Version | Notes |
|---|---|---|
| Chrome, Edge, other Chromium browsers | 134+ | V8 v13.8 |
| Node.js | 24.0.0+ | Bundles V8 13.6+; no flag required |
| Deno | 1.37+ for using, 2.2.10+ for await using | |
| Bun | 1.0.23+ | |
| Firefox | 141+ | |
| Safari | Not yet supported | |
| TypeScript | 5.2+ | Type-checks using/await using against Disposable/AsyncDisposable |
| Babel | Supported | Transform-based, works on any target |
| core-js | core-js/proposals/explicit-resource-management | Polyfill for engines without native support |
using x = null and using x = undefined are permitted no-ops. The specification skips the disposal lookup when the bound value is nullish, so a resource factory that returns null will not throw at the using declaration, and cleanup for that binding is simply skipped.
Related Topics
- FEE-300 JavaScript Core & Runtime Overview
- FEE-301 Event Loop & Async Model
- FEE-10001 Temporal API
- FEE-10006 Async Context
References
- TC39 proposal-explicit-resource-management — official proposal repository with specification text and motivation
- TypeScript 5.2 Release Notes —
usingDeclarations and Explicit Resource Management — TypeScript implementation details and type system integration - MDN:
usingstatement — syntax reference and cross-runtime compatibility table - MDN:
await usingstatement — async disposal syntax reference - MDN: Symbol.dispose — browser compatibility and API reference
- MDN: Symbol.asyncDispose — async disposal reference
- MDN: SuppressedError — error type reference
- V8, "JavaScript's New Superpower: Explicit Resource Management," v8.dev (2025) — verified shipping versions (Chromium 134 / V8 v13.8) and implementation notes