Explicit Resource Management in JavaScript: using, await using and DisposableStack
Clean up files, connections, locks and timers automatically with using and await using: Symbol.dispose and Symbol.asyncDispose, reverse disposal order, behavior on errors and SuppressedError, DisposableStack and AsyncDisposableStack, disposable iterators, browser support and when to use it.
kvi5hnuCode Sprout team member7 min readOn this page
Programs constantly acquire things that must be released: file handles, database connections, locks, event subscriptions, temporary directories. Forgetting to release them causes leaks, and releasing them correctly on every path (normal exit, early return, thrown error) has traditionally meant a try...finally for each resource. Explicit resource management adds the using and await using declarations, which release a resource automatically when the enclosing block ends. C# (using), Python (with) and Java (try-with-resources) have had similar features for years.
The feature reached Stage 4 at TC39 (the course lists it under ES2027, as in articles 19 and 38) and already ships in Chromium-based browsers, Firefox and Node.js; Safari support is in progress. TypeScript (5.2+) and Babel can compile it for older targets.
The problem with try...finally
const db = await openDatabase();
try {
const file = await openFile("export.csv");
try {
await file.write(await db.exportCsv());
} finally {
await file.close();
}
} finally {
await db.close();
}
Every resource adds a level of nesting, the cleanup code sits far from the acquisition, and it's easy to close things in the wrong order or forget one. With await using:
await using db = await openDatabase();
await using file = await openFile("export.csv");
await file.write(await db.exportCsv());
// file is closed, then db, when the enclosing block (or module) ends
Disposable objects: Symbol.dispose
A disposable object has a method under the well-known symbol Symbol.dispose (article 19). using calls it when the variable goes out of scope:
function openFile(name) {
console.log("open", name);
return {
read: () => `contents of ${name}`,
[Symbol.dispose]() {
console.log("close", name);
},
};
}
{
using config = openFile("config.json");
using log = openFile("app.log");
console.log(config.read());
}
console.log("after the block");
open config.json
open app.log
contents of config.json
close app.log
close config.json
after the block

Rules:
- Resources are disposed in reverse order of declaration (last in, first out), so later resources, which may depend on earlier ones, are closed first.
- Disposal happens however the block exits: reaching the end,
return,break,continueor a thrown exception. usingbindings are constant, likeconst; you can't reassign them.using x = nullorundefinedis allowed and simply disposes nothing, which helps with optional resources. Any other value without a[Symbol.dispose]method throws aTypeErrorat the declaration.usingworks in any block, function body,for...ofloop head and module top level, but not at the top level of a classic script, and not with destructuring (using { a } = objis a SyntaxError).
Disposal on errors
function lock(name) {
console.log("acquire", name);
return { [Symbol.dispose]: () => console.log("release", name) };
}
function transfer() {
using l = lock("account-42");
throw new Error("insufficient funds");
}
try {
transfer();
} catch (err) {
console.log("caught:", err.message);
}
acquire account-42
release account-42
caught: insufficient funds
If the body throws and a dispose method throws too, neither error is lost. The caller receives a SuppressedError: its error property is the disposal error and its suppressed property is the error that was already propagating:
function brokenResource() {
return {
[Symbol.dispose]() {
throw new Error("close failed");
},
};
}
try {
using r = brokenResource();
throw new Error("work failed");
} catch (err) {
console.log(err.name);
console.log("error:", err.error.message);
console.log("suppressed:", err.suppressed.message);
}
SuppressedError
error: close failed
suppressed: work failed
Even when one dispose method throws, the remaining resources are still disposed.
await using and Symbol.asyncDispose
Many cleanups are asynchronous: flushing a file, closing a network connection, committing a transaction. await using calls [Symbol.asyncDispose]() and awaits its promise at block exit. It's allowed wherever await is: in async functions and at the top level of modules.
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function connect(url) {
await delay(5);
console.log("connected to", url);
return {
query: (sql) => `rows for: ${sql}`,
async [Symbol.asyncDispose]() {
await delay(5);
console.log("connection closed");
},
};
}
async function main() {
{
await using db = await connect("db://reports");
console.log(db.query("SELECT * FROM sales"));
}
console.log("after the block: connection is already closed");
}
main();
connected to db://reports
rows for: SELECT * FROM sales
connection closed
after the block: connection is already closed
Note the two awaits in await using db = await connect(...): the right-hand await waits for the connection to open; await using arranges to wait for it to close. If an object only has a sync [Symbol.dispose], await using falls back to it.
DisposableStack: managing many resources
Sometimes you don't know in advance how many resources you'll have, or a resource doesn't implement Symbol.dispose. DisposableStack (and AsyncDisposableStack) collects cleanups and runs them in reverse order when the stack itself is disposed:
| Method | What it does |
|---|---|
stack.use(resource) | adds a disposable object and returns it |
stack.adopt(value, onDispose) | adds a non-disposable value with a cleanup function, called as onDispose(value) |
stack.defer(fn) | adds a plain cleanup callback |
stack.move() | transfers all registered cleanups to a new stack, leaving this one empty |
stack.dispose() | runs all cleanups now, in reverse order |
function openFile(name) {
console.log("open", name);
return { name, [Symbol.dispose]: () => console.log("close", name) };
}
function process(names) {
using stack = new DisposableStack();
const files = names.map((n) => stack.use(openFile(n)));
const timer = stack.adopt(setInterval(() => {}, 1000), (id) => {
clearInterval(id);
console.log("timer cleared");
});
stack.defer(() => console.log("temp dir removed"));
console.log("processing", files.length, "files");
}
process(["a.csv", "b.csv"]);
open a.csv
open b.csv
processing 2 files
temp dir removed
timer cleared
close b.csv
close a.csv
Handing resources over with move()
A constructor or factory often opens several resources, and if the third one fails, the first two must be closed. move() makes that safe: register everything on a stack declared with using, then move the cleanups out only once construction has succeeded:
function openFile(name, fail = false) {
if (fail) throw new Error(`cannot open ${name}`);
console.log("open", name);
return { name, [Symbol.dispose]: () => console.log("close", name) };
}
function openPair(a, b, failSecond) {
using stack = new DisposableStack();
const first = stack.use(openFile(a));
const second = stack.use(openFile(b, failSecond));
const cleanup = stack.move(); // success: keep them open
return { first, second, [Symbol.dispose]: () => cleanup.dispose() };
}
try {
openPair("in.txt", "out.txt", true);
} catch (err) {
console.log("setup failed:", err.message);
}
{
using pair = openPair("in.txt", "out.txt", false);
console.log("working with", pair.first.name, "and", pair.second.name);
}
open in.txt
close in.txt
setup failed: cannot open out.txt
open in.txt
open out.txt
working with in.txt and out.txt
close out.txt
close in.txt
On failure, the using stack closes in.txt automatically. On success, move() empties the stack before it's disposed, and the returned object owns the cleanup instead.
Built-in disposables
The proposal also made some existing objects disposable:
- Iterators created by built-ins and generators have
[Symbol.dispose](), which calls theirreturn()method (article 92), sousing it = gen()guarantees the generator'sfinallyblocks run. - Async generators have
[Symbol.asyncDispose](). - Node.js adds disposal to many APIs, including file handles from
fs/promises(await using fh = await open(path)), timers and some stream and worker objects. - In browsers, web platform APIs are being updated gradually; until then,
DisposableStack.adoptwraps anything with a close method.
import { open } from "node:fs/promises";
async function firstLine(path) {
await using file = await open(path); // closed automatically
for await (const line of file.readLines()) return line;
}
When to use it
Use using/await using when a value has a lifetime tied to a scope: files, sockets, database connections and transactions, locks, temporary subscriptions, performance spans, test fixtures. To make your own classes work with it, add a [Symbol.dispose]() (or [Symbol.asyncDispose]()) method, usually alongside an existing close():
class Subscription {
constructor(target, type, handler) {
target.addEventListener(type, handler);
this.close = () => target.removeEventListener(type, handler);
}
[Symbol.dispose]() {
this.close();
}
}
Don't use it for values that live beyond the block (store them on an object and dispose them when the owner is disposed), and remember that disposal only happens when the block exits. A using at the top level of a long-running module keeps the resource open until the module's evaluation ends.
Common questions
Is using the same as a destructor or garbage collection?
No. Disposal is deterministic: it happens exactly when the block exits, not whenever the garbage collector runs. For GC-based cleanup, see FinalizationRegistry (article 78), which gives no timing guarantees.
In what order are resources disposed?
In reverse order of declaration, so a resource declared later (which may depend on an earlier one) is disposed first.
What happens if Symbol.dispose throws?
The remaining resources are still disposed. If the block was already throwing, the caller gets a SuppressedError that contains both errors (error and suppressed).
Can I use it today?
In current Chromium-based browsers, Firefox and Node.js, yes. For Safari or older runtimes, compile it with TypeScript 5.2+ or Babel, and load a polyfill for DisposableStack and the symbols.
Summary
using x = resourcecallsx[Symbol.dispose]()when the enclosing block exits, however it exits.await usingcalls and awaits[Symbol.asyncDispose]()(falling back to[Symbol.dispose]); it's allowed in async functions and modules.- Resources are disposed in reverse order;
null/undefinedare skipped, and other non-disposables throw aTypeError. - Errors during disposal don't stop other disposals; combined failures surface as
SuppressedError. DisposableStack/AsyncDisposableStackcollect cleanups withuse,adoptanddefer, andmove()enables all-or-nothing setup.- Iterators, generators and many Node APIs are already disposable.
Review quiz
Check your understanding of the event loop, promises, chaining, combinators, async/await, async iteration and using: Part 13 review quiz: Asynchronous JavaScript.
Practice Questions
What does this print?
function res(n) {
return { [Symbol.dispose]: () => console.log("dispose", n) };
}
{
using a = res(1);
using b = res(2);
console.log("body");
}
Answer
body, dispose 2, dispose 1. Disposal runs at block exit in reverse declaration order.
Rewrite getRows with await using so the connection always closes, even when the query fails. Assume conn has an async close() method.
async function getRows(sql) {
const conn = await connect();
const rows = await conn.query(sql);
await conn.close();
return rows;
}
Answer
If the connection object doesn't implement Symbol.asyncDispose, adopt it on a stack:
async function getRows(sql) {
await using stack = new AsyncDisposableStack();
const conn = stack.adopt(await connect(), (c) => c.close());
return await conn.query(sql);
}
If it does implement Symbol.asyncDispose, it's simply:
async function getRows(sql) {
await using conn = await connect();
return await conn.query(sql);
}
In the original code, a failing query skipped close().
Why does this throw a TypeError?
using settings = { theme: "dark" };
Answer
The value isn't null or undefined and has no [Symbol.dispose] method, so using can't dispose it. Use const for ordinary values.
A function opens three files with DisposableStack, and the third open throws. What happens to the first two?
Answer
If the stack was declared with using, the thrown error exits the function's block, so the stack is disposed and the first two files are closed, in reverse order. That's the all-or-nothing pattern; on success, stack.move() transfers the cleanups to the caller.
Previous: Async Iteration in JavaScript: for await...of, Async Generators and Streams
Next: JavaScript Property Attributes: Writable, Enumerable, Configurable and Object.defineProperty

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.