JavaScript and TypeScript developers often treat using and await using as cosmetic shorthand for try...finally, but their real value is fixing two failure modes that manual finally blocks routinely hide. By binding teardown to lexical scope, unwinding multiple resources in reverse declaration order, and chaining secondary failures into SuppressedError, explicit resource management turns cleanup from a fragile control-flow habit into a runtime guarantee.
Why Manual finally Blocks Break Under Failure
Writing try...finally works cleanly for a single resource, yet real backend handlers rarely stop at one. Consider a route that checks out a database client, creates a temporary working file, and streams results back to the caller. Putting both cleanup calls inside a single finally block introduces an immediate trap: if deleting the temporary file throws an I/O error, execution jumps out of finally before client.release() ever runs, leaking a connection from the pool.
Fixing that leak manually requires nesting one try...finally inside another for every resource you acquire. Even then, standard JavaScript control flow has a deeper blind spot: an exception thrown inside finally silently replaces any exception already thrown inside try. When a query fails due to a broken network socket and the subsequent cleanup call also throws on that dead socket, the original domain failure vanishes completely, leaving only a generic teardown error in your logs.
Scope-Bound Cleanup With using and await using

Explicit Resource Management—standardized in ECMAScript and supported since TypeScript 5.2—shifts cleanup responsibility from the caller's control flow to the resource's lexical lifetime. Any object implementing [Symbol.dispose]() can be declared with using, and any object implementing [Symbol.asyncDispose]() can be declared with await using.
import type { Pool, PoolClient } from "pg";
async function checkoutClient(pool: Pool) {
const client: PoolClient = await pool.connect();
return {
client,
[Symbol.dispose]() {
client.release();
},
};
}
export async function archiveOrder(pool: Pool, orderId: string) {
using lease = await checkoutClient(pool);
return await lease.client.query(
"UPDATE orders SET archived = true WHERE id = $1",
[orderId],
);
} // lease[Symbol.dispose]() runs on return or throw
Notice the subtle distinction in using lease = await checkoutClient(pool). The await on the right-hand side waits for connection acquisition, while using on the left governs synchronous disposal (client.release() simply hands the client back to memory). When teardown itself performs asynchronous I/O—such as flushing a file handle, closing an HTTP server, or releasing a Redis lock—use await using with [Symbol.asyncDispose]() instead. Never return a Promise from [Symbol.dispose](), because using will not await it, and even await using only awaits promises returned from [Symbol.asyncDispose]().
When you declare several using or await using bindings in the same block, the runtime tracks them in an internal list and disposes them in last-in, first-out (LIFO) order when the scope exits. If a dependent stream reader is declared after its underlying file handle, the reader is always released before the file closes—and a failure while closing the reader will not skip closing the file. Both keywords also accept null and undefined, so conditional resources do not need extra null guards at exit.
Preserving Root Causes With SuppressedError and DisposableStack
Because every registered disposer runs even when earlier steps fail, JavaScript needs a way to report two exceptions at once without losing either. Enter SuppressedError, a built-in Error subclass created when disposal throws while another error is already unwinding the stack. Its error property holds the latest teardown failure, while suppressed holds the original error that got displaced.
If your logging middleware or error tracker only serializes err.message and err.cause, SuppressedError can still catch you off guard. Central error reporters should explicitly walk err.suppressed alongside err.cause so the primary crash inside your business logic remains visible right next to the failed cleanup step.
Lexical declarations cover most functions, but two situations still feel awkward with using alone: wrapping third-party objects that do not implement Symbol.dispose yet, and assembling resources conditionally or inside class constructors. DisposableStack and AsyncDisposableStack fill both gaps without subclassing or mutating third-party prototypes:
export async function exportReport(stream: ReadableStream<Uint8Array>) {
await using stack = new AsyncDisposableStack();
const reader = stack.adopt(stream.getReader(), (r) => r.releaseLock());
stack.defer(async () => {
await flushMetrics();
});
const { value } = await reader.read();
return value;
}
Here, adopt() pairs an existing ReadableStreamDefaultReader with its cleanup callback, and defer() schedules standalone teardown work in the same LIFO queue. If you are initializing multiple sockets inside a factory or constructor, calling stack.move() at the very end transfers ownership to a new stack—guaranteeing automatic rollback if initialization throws halfway through, while keeping the resources alive once construction succeeds.
Adopting Explicit Resource Management Today
Runtime support has matured rapidly across server and desktop environments. V8 and SpiderMonkey ship native using, await using, DisposableStack, and SuppressedError in Chrome 134+, Firefox 141+, and Node.js 24. On the Node.js side, built-in resources including fs.FileHandle, streams, and timers began exposing Symbol.dispose and Symbol.asyncDispose back in Node.js 20.4, meaning native Node objects already plug directly into await using without custom wrappers.
For browser bundles, caution is still warranted: Safari support remains in preview, so production frontends and older Node LTS services must still compile using declarations down via TypeScript 5.2+ or Babel. To avoid compiler complaints in TypeScript, include "esnext.disposable" (or "esnext") in compilerOptions.lib, and load a lightweight polyfill such as core-js when targeting runtimes that lack Symbol.dispose and SuppressedError.
Start small where leaks hurt most: database pool checkouts, stream locks, temporary directories in integration tests, and distributed mutexes. Keep disposers idempotent so repeated calls are harmless, update your error logger to unwrap SuppressedError, and let lexical scope enforce the cleanup discipline that code review alone never catches every time.




Loading comments…