How to Run Async Cleanup With await using in JavaScript
Run async cleanup with await using: implement Symbol.asyncDispose, release files, locks and connections on every exit path, and stack resources safely.

Cleanup code is easy to forget and hard to get right. You open a file, take a lock or start a transaction, and then every path out of the function, a return, a throw or an early exit, has to release it. The try and finally pattern does that, and it nests badly when there are several resources, and each finally that itself awaits can throw and hide the original error. await using is the language's answer. It declares a variable whose cleanup runs automatically when the scope ends, in reverse order of declaration, even when an error is thrown. This post shows how await using and Symbol.asyncDispose work in Node.js 24, how to write a disposable resource, how errors behave during cleanup and where the feature fits next to try and finally. It is part of the explicit resource management feature, so check the support table for your browsers before relying on it. It builds on writing async code that is easy to cancel.
The problem it solves
Here is cleanup with try and finally for two resources, a lock and a connection. The nesting grows with each one.
async function transfer(lock, db) {
await lock.acquire();
try {
const connection = await db.connect();
try {
await connection.query("UPDATE accounts SET balance = balance - 10");
} finally {
await connection.close();
}
} finally {
lock.release();
}
}Every resource adds a level of indentation and a finally, and moving the cleanup away from the line that acquires it makes mistakes likely: a new early return in the middle, a resource acquired outside the try. The structure also gives no help when two cleanups both fail.
A disposable resource
An object is disposable when it has a method under the well-known symbol Symbol.asyncDispose, which returns a promise. When a await using variable goes out of scope, the runtime calls that method and waits for it.
export function openConnection(name) {
console.log(`open ${name}`);
return {
name,
async query(sql) {
console.log(`${name}: ${sql}`);
},
async [Symbol.asyncDispose]() {
await new Promise((resolve) => setTimeout(resolve, 5));
console.log(`close ${name}`);
},
};
}The method name is computed from a symbol, which is why it is written in square brackets. Node.js 24 defines Symbol.dispose and Symbol.asyncDispose as part of this feature, and Node.js 18.18 and later also defines them so libraries can add disposal ahead of syntax support.
Using it
Declare the resource with await using. The cleanup runs when the enclosing block ends, whichever way it ends.
import { openConnection } from "./resource.js";
async function work() {
await using conn = openConnection("db1");
await conn.query("SELECT 1");
console.log("work finished");
}
await work();
console.log("after work");open db1
db1: SELECT 1
work finished
close db1
after workThe close db1 line comes after work finished, which is the point where the function body ended, and before after work, since the function's promise resolves only after the disposal has been awaited. There is no finally and no close call in the function. The await in await using matters: it marks that disposal is asynchronous, and the declaration must be inside an async function or at the top level of a module.
Reverse order, and several resources
Resources are disposed in the reverse of the order they were declared, last first. That matches how dependencies usually nest: a connection opened after the lock should close before the lock is released.
import { openConnection } from "./resource.js";
async function work() {
await using first = openConnection("first");
await using second = openConnection("second");
console.log("working with both");
}
await work();open first
open second
working with both
close second
close firstThe flat structure replaces the nested try and finally, and adding a third resource is one more line.
Disposal runs on errors too
If the body throws, the resources declared so far are still disposed before the error propagates to the caller.
import { openConnection } from "./resource.js";
async function work() {
await using conn = openConnection("db2");
throw new Error("query failed");
}
try {
await work();
} catch (error) {
console.log("caught:", error.message);
}open db2
close db2
caught: query failedThe cleanup finished first, and then the original error reached the catch. This is the same order as finally, with less code.
What happens when disposal itself fails
If the body throws and a disposal also throws, the errors are combined into a SuppressedError, whose error property holds the later error and suppressed holds the earlier one, so neither is lost. When only the disposal throws, that error propagates as usual.
async function work() {
await using bad = {
async [Symbol.asyncDispose]() {
throw new Error("cleanup failed");
},
};
throw new Error("body failed");
}
try {
await work();
} catch (error) {
console.log(error.name);
console.log(error.error.message, "|", error.suppressed.message);
}SuppressedError
cleanup failed | body failedWith a manual finally that awaits something which throws, the cleanup error silently replaces the original one, and the cause of the failure is lost. The SuppressedError shape keeps both, which is a real improvement in debugging.
Make a resource from a cleanup function
Not every cleanup deserves a class. For a one-off, build the disposable object inline from the function that does the cleanup.
export function disposable(value, cleanup) {
return {
value,
async [Symbol.asyncDispose]() {
await cleanup(value);
},
};
}
async function main() {
await using timer = disposable(
setInterval(() => {}, 1000),
async (id) => {
clearInterval(id);
console.log("interval cleared");
}
);
console.log("doing work with", typeof timer.value);
}
await main();doing work with object
interval clearedThe timer id is an object in Node.js, which is why typeof prints object. A browser would print number. The helper is a small adapter that makes any cleanup function usable with the new syntax, and many libraries expose one.
Combine several cleanups with AsyncDisposableStack
When resources are acquired conditionally or in a loop, a stack object collects cleanups and disposes them in reverse order. AsyncDisposableStack is part of the same feature, with use, adopt and defer methods to register resources and cleanup functions.
const stack = new AsyncDisposableStack();
stack.defer(async () => console.log("cleanup 1"));
stack.defer(async () => console.log("cleanup 2"));
console.log("registered");
await stack.disposeAsync();registered
cleanup 2
cleanup 1Use it when the number of resources is not known when you write the code, such as opening one connection per shard in a loop. The stack can also be moved out of a function with move() when ownership passes to the caller.
Where it fits, and where it does not
await using replaces try and finally for resources with an owner and a scope: files, connections, locks, temporary directories, subscriptions. It does not replace finally for arbitrary code that has to run after a block, such as resetting a flag, where a finally is shorter and clearer. It cannot dispose a resource that outlives the scope, since disposal happens at block exit. And it is not available everywhere yet: Node.js 24, Chrome 134 and Firefox 141 support the syntax, Safari support lags, and TypeScript 5.2 and later compile it down for older targets. Check the [MDN reference for await using](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/await_using) for the current table before you adopt it in code that runs in browsers.
Disposal and cancellation together
Cleanup that waits can hang, and a hanging cleanup is worse than a failing one, because the scope never finishes. Give disposal methods a bounded wait. If closing a connection involves a network round trip, set a timeout inside [Symbol.asyncDispose] so a dead peer cannot stall the function that owns the resource, and let the method log and give up when the limit passes. Pair this with the signal-aware style from the cancellation posts: a canceled operation throws its reason, the await using variables are disposed on the way out, and the caller sees the original reason once the cleanup is complete.
Testing disposable resources
A disposable is easy to test directly. Create the resource, call await resource[Symbol.asyncDispose]() and assert on the state afterward. Then test the scope behavior with a function that uses await using and a resource that records its calls: assert that disposal ran after a normal return, after a thrown error and after an early return, and that the order of two resources is reversed. A test for the failing disposal checks that a SuppressedError carries both messages. Those tests are short, and they pin down the behavior that calling code relies on when it stops writing finally blocks.


