Skip to content
FEE
Frontend Engineering Essentials
Senior Level
Hardened· 2026-07

[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.

js
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.

js
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.

js
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.

js
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:

js
// 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:

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

Scenariotry/finallyusing
Cleanup on normal exitYes (with finally)Always
Cleanup on throwYes (with finally)Always
Forgetting cleanupPossibleImpossible — cleanup is on the class
Both body and dispose throwOriginal error lostBoth preserved in SuppressedError
Multiple resourcesNested blocksLinear declarations
Cleanup locationCall siteClass definition

Example ​

1. Basic using with a database connection ​

js
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 ​

js
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 ​

js
// 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.

js
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.

js
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.

js
[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:

LanguageSyntaxInterface
C++Destructor (~T())Runs when scope exits
Pythonwith statement__enter__ / __exit__
C#using statementIDisposable.Dispose()
Javatry-with-resourcesAutoCloseable.close()
Swiftdefer statementArbitrary statement
Kotlin.use {} extensionCloseable.close()
Godefer statementArbitrary statement
JavaScriptusing / 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":

js
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:

js
// The original error "body threw" is replaced by "cleanup threw"
// You will never see "body threw" in your logs

The proposal introduces SuppressedError to preserve both:

js
// 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:

  1. The finally block runs first.
  2. The using dispose actions run after finally, in reverse declaration order.
js
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.

js
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.suppressed holds the original body error (the one that was suppressed).
  • err.error holds 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.

js
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 printed

The four methods on DisposableStack:

MethodWhat it acceptsWhen to use
.use(disposable)Any object with [Symbol.dispose]()Transferring ownership of a disposable
.adopt(value, fn)Any value + cleanup callbackNon-disposable resources (raw sockets, native handles)
.defer(fn)A zero-argument functionArbitrary side effects at cleanup time
.move()NothingTransfer 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:

ts
// 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 Disposable

TypeScript 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 / toolVersionNotes
Chrome, Edge, other Chromium browsers134+V8 v13.8
Node.js24.0.0+Bundles V8 13.6+; no flag required
Deno1.37+ for using, 2.2.10+ for await using
Bun1.0.23+
Firefox141+
SafariNot yet supported
TypeScript5.2+Type-checks using/await using against Disposable/AsyncDisposable
BabelSupportedTransform-based, works on any target
core-jscore-js/proposals/explicit-resource-managementPolyfill 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.

References ​