Sub topic 12
AsyncDisposableStack for Async Resource Groups
This chapter assumes you already know await using, the reverse disposal order, SuppressedError, and the synchronous DisposableStack API (use, adopt, defer, move). AsyncDisposableStack is the asynchronous version of that API. It holds a group of resources whose cleanup may take time, such as network connections, file handles, temporary directories, or transactions, and it awaits each cleanup step in turn when the group is disposed.
Why a Separate Async Stack Exists
A DisposableStack calls its callbacks synchronously. If you give it a callback that returns a promise, the stack calls the callback, ignores the promise, and moves on. Your cleanup then runs in the background, nobody waits for it, and a rejection from it becomes an unhandled rejection.
An AsyncDisposableStack awaits each cleanup operation before it starts the next one. It is itself an async disposable: it has a [Symbol.asyncDispose] method and no [Symbol.dispose] method. You declare it with await using, or you call await stack.disposeAsync() yourself.
| Aspect | DisposableStack | AsyncDisposableStack |
|---|---|---|
| Declared with | `using` | `await using` |
| Disposal method | `dispose()` | `disposeAsync()` (returns a promise) |
| Protocol symbol | `Symbol.dispose` | `Symbol.asyncDispose` |
| `use()` accepts | objects with `Symbol.dispose` | objects with `Symbol.asyncDispose` or `Symbol.dispose` |
| Callbacks for `adopt`/`defer` | synchronous | may return a promise, which is awaited |
| Order of cleanup | reverse registration | reverse registration, one step at a time |
The API at a Glance
use(value)registers a disposable and returns it. The stack prefersvalue[Symbol.asyncDispose]. If that method is missing, it falls back tovalue[Symbol.dispose].nullandundefinedare accepted and ignored. Any other value without one of these methods throws aTypeErrorright away, at registration time.adopt(value, onDisposeAsync)registers a value that is not disposable, together with a callback. At disposal the stack calls the callback with that value.adoptreturnsvalue.defer(onDisposeAsync)registers a callback that takes no arguments.move()returns a newAsyncDisposableStackthat holds all the registered entries. The original stack is left empty and marked as disposed.disposeAsync()runs every entry in reverse order and returns a promise. Calling it again after the first time does nothing.disposedis a getter that istrueonce the stack has been disposed or moved.
After a stack is disposed, calling use, adopt, defer, or move throws a ReferenceError.
A Variable Number of Async Resources
An await using declaration binds one resource. When the number of resources is known only at runtime, a stack lets you bind all of them to one scope.
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
class Connection {
#name;
#open = true;
constructor(name) {
this.#name = name;
}
static async open(name) {
await delay(5);
if (name === "bad") throw new Error(`cannot open ${name}`);
console.log(`open ${name}`);
return new Connection(name);
}
get name() {
return this.#name;
}
async [Symbol.asyncDispose]() {
if (!this.#open) return;
this.#open = false;
await delay(5);
console.log(`close ${this.#name}`);
}
}
async function report(regions) {
await using stack = new AsyncDisposableStack();
const conns = [];
for (const region of regions) {
conns.push(stack.use(await Connection.open(region)));
}
console.log(`querying ${conns.map((c) => c.name).join(", ")}`);
}
report(["eu", "us", "ap"]);
// open eu
// open us
// open ap
// querying eu, us, ap
// close ap
// close us
// close euEach connection is registered right after it opens. If opening ap threw, the stack would still close us and eu when report exits, because only the connections that actually opened were registered.
How Disposal Proceeds
Disposal is sequential. The stack does not start closing the second connection until the first close has settled. This matches how nested await using declarations behave, and it keeps dependencies safe: a transaction registered after its connection is always finished before the connection closes.
A resource registered through use that has only Symbol.dispose is called synchronously. The stack still awaits once before it moves to the next entry, so you can mix synchronous resources such as locks with asynchronous ones in one stack.
Adapting Async APIs with adopt and defer
Many existing APIs return plain values and have a separate async cleanup function. adopt connects the two. The example below runs on Node.js 24 or later as an ES module (save it as job.mjs).
import { mkdtemp, rm, writeFile, readdir } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
async function runJob() {
await using stack = new AsyncDisposableStack();
const dir = stack.adopt(
await mkdtemp(join(tmpdir(), "job-")),
async (path) => {
await rm(path, { recursive: true, force: true });
console.log("temp dir removed");
}
);
stack.defer(async () => {
const files = await readdir(dir);
console.log(`job finished with ${files.length} file(s)`);
});
await writeFile(join(dir, "data.txt"), "hello");
}
await runJob();
// job finished with 1 file(s)
// temp dir removedThe deferred callback was registered last, so it runs first and can still read the directory. Register resources in the order they depend on each other, and cleanup will happen in the opposite order.
Transferring Ownership After Async Setup
Async factories have the same rollback problem as synchronous ones, and it is usually worse because each step can fail on the network. The move() pattern works the same way in async code: the stack cleans up if setup fails, and it hands the resources to the caller if setup succeeds.
async function createPool(names) {
await using stack = new AsyncDisposableStack();
const conns = [];
for (const name of names) {
conns.push(stack.use(await Connection.open(name)));
}
const owned = stack.move();
return {
conns,
async [Symbol.asyncDispose]() {
await owned.disposeAsync();
},
};
}
async function main() {
try {
await using pool = await createPool(["a", "bad", "c"]);
} catch (e) {
console.log(`setup failed: ${e.message}`);
}
await using pool = await createPool(["a", "b"]);
console.log(`pool has ${pool.conns.length} connections`);
}
main();
// open a
// close a
// setup failed: cannot open bad
// open a
// open b
// pool has 2 connections
// close b
// close aWhen bad throws, createPool exits and the original stack closes a. On success, move() empties the original stack, so its await using disposal at the end of the function does nothing, and the caller now owns the connections.
Errors from Several Cleanups
Every cleanup runs even if an earlier one fails. Errors are combined the same way they are for nested await using declarations. Each new error wraps the error collected so far in a SuppressedError.
async function demo() {
const stack = new AsyncDisposableStack();
stack.defer(async () => { throw new Error("A failed"); });
stack.defer(async () => { throw new Error("B failed"); });
try {
await stack.disposeAsync();
} catch (e) {
console.log(e instanceof SuppressedError); // true
console.log(e.error.message); // "A failed"
console.log(e.suppressed.message); // "B failed"
}
console.log(stack.disposed); // true
}
demo();B runs first and fails. A runs next and fails too, so A's error becomes error and B's error becomes suppressed. If only one callback had failed, disposeAsync would reject with that plain Error, without a wrapper. Code that walks the chain should handle both shapes.
Common Mistakes
Declaring the stack with using
using stack = new AsyncDisposableStack() throws a TypeError at the declaration, because the stack has no Symbol.dispose method. Use await using.
Expecting parallel cleanup
Ten connections that each take 100 ms to close need about a second to dispose. If the resources do not depend on each other, register one callback that closes them all at once:
async function closeAllAtOnce(conns) {
await using stack = new AsyncDisposableStack();
stack.defer(async () => {
const results = await Promise.allSettled(
conns.map((c) => c[Symbol.asyncDispose]())
);
const errors = results
.filter((r) => r.status === "rejected")
.map((r) => r.reason);
if (errors.length) throw new AggregateError(errors, "close failed");
});
}Promise.allSettled makes sure every close finishes and that no error is lost. Promise.all would reject as soon as the first close failed and drop the rest of the errors.
Forgetting to dispose a manually created stack
A stack that you create with const and never dispose does nothing at all. Bind it with await using, move it to an owner who will dispose it, or call disposeAsync() in a finally block.
Registering after disposal
Callbacks that run later, such as event handlers, sometimes try to call stack.defer after the scope has exited. That call throws a ReferenceError. Check stack.disposed before registering, or design the code so that registration happens only during setup.
Exercise
A function runs await using stack = new AsyncDisposableStack();, then calls stack.use(lock) where lock has only [Symbol.dispose] that logs "unlock", then stack.adopt(42, async (n) => console.log("adopted", n)), then stack.defer(() => console.log("deferred")). What is logged when the function returns, and why is the synchronous lock accepted?
Show answer
"deferred", then "adopted 42", then "unlock". Entries are disposed in reverse registration order, and each one is awaited before the next starts. The lock is accepted because AsyncDisposableStack.prototype.use falls back to Symbol.dispose when Symbol.asyncDispose is missing.
Exercise
In createPool, a teammate moves stack.move() to the top of the function, before the loop that opens connections. What breaks?
Show answer
The original stack is empty and marked disposed right away, so stack.use(...) inside the loop throws a ReferenceError on the first connection. Even if registration went to owned instead, a failure partway through setup would no longer trigger rollback, because owned is not bound to the function's scope and the connections that already opened would leak.
Exercise
Two deferred async callbacks are registered: first X, which rejects with "X", then Y, which rejects with "Y". After await stack.disposeAsync() rejects with e, what are e.error.message and e.suppressed.message?
Show answer
Y runs first and its error is recorded. X runs second, and its error wraps Y's error. So e.error.message is "X" and e.suppressed.message is "Y".