Sub topic 12
AsyncDisposableStack for Async Resource Groups
This chapter assumes you know await using, DisposableStack and its use, adopt, defer, and move methods, and how SuppressedError reports cleanup failures. AsyncDisposableStack is the asynchronous version of DisposableStack. Use it when the group of resources you manage includes at least one resource whose cleanup returns a promise.
The Working Model
An AsyncDisposableStack is a container that records cleanup steps. When you dispose it, it runs those steps in reverse order of registration. It awaits each step before starting the next one. It does not run them in parallel. This matters when a later resource depends on an earlier one, such as a transaction that must finish before its connection closes.
The stack is itself async disposable, so you declare it with await using:
async function demo() {
await using stack = new AsyncDisposableStack();
stack.defer(async () => console.log("cleanup ran"));
}
demo();How It Differs from DisposableStack
| Feature | DisposableStack | AsyncDisposableStack |
|---|---|---|
| Declared with | `using` | `await using` |
| `use(value)` accepts | `Symbol.dispose` | `Symbol.asyncDispose` or `Symbol.dispose` |
| `adopt` and `defer` callbacks | Synchronous | May return a promise, which is awaited |
| Manual disposal | `dispose()` | `disposeAsync()`, which returns a promise |
| Dispose symbol | `Symbol.dispose` | `Symbol.asyncDispose` |
| `move()` returns | `DisposableStack` | `AsyncDisposableStack` |
use falls back to Symbol.dispose when Symbol.asyncDispose is missing. This lets you mix sync and async resources in one stack. Like using, use(null) and use(undefined) are ignored. Passing any other value that has no dispose method throws a TypeError.
A Worked Example: Opening a Group of Connections
The function below opens a variable number of resources. If any step fails partway through, the stack closes everything opened so far. If every step succeeds, move() hands ownership to the caller.
function makeResource(name, delayMs) {
return {
name,
async [Symbol.asyncDispose]() {
await new Promise((resolve) => setTimeout(resolve, delayMs));
console.log(`closed ${name}`);
},
};
}
async function openAll(names) {
await using stack = new AsyncDisposableStack();
const resources = names.map((name, i) =>
stack.use(makeResource(name, 10 * (i + 1)))
);
stack.defer(async () => console.log("group released"));
const owned = stack.move();
return {
resources,
async [Symbol.asyncDispose]() {
await owned.disposeAsync();
},
};
}
async function main() {
await using group = await openAll(["db", "cache", "queue"]);
console.log(group.resources.map((r) => r.name).join(", "));
}
main();
// db, cache, queue
// group released
// closed queue
// closed cache
// closed dbAfter move(), the original stack is empty and marked disposed. When openAll returns, its await using disposes that empty stack and nothing happens. The owned stack now holds all the cleanup steps and runs them when main exits.
Adapting Promise-Based APIs
Many libraries expose a close() method that returns a promise but do not implement Symbol.asyncDispose. Wrap these values with adopt:
const client = { async close() { console.log("client closed"); } };
async function run() {
await using stack = new AsyncDisposableStack();
const c = stack.adopt(client, async (value) => value.close());
console.log("using client", c === client);
}
run();
// using client true
// client closedCommon Errors
- Declaring it with plain
using.AsyncDisposableStackhas noSymbol.dispose, sousing stack = new AsyncDisposableStack()throws aTypeError. - Calling
disposeAsync()without awaiting it. Cleanup keeps running in the background, and any rejection goes unhandled. - Expecting parallel cleanup. The steps run one after another. If you need concurrent cleanup,
defera single callback that callsPromise.all. - Using the stack after
move()or disposal. Callinguse,adopt,defer, ormoveon a disposed stack throws aReferenceError. - Losing errors. If several cleanup steps reject, the stack keeps running the remaining steps and then rejects with nested
SuppressedErrorobjects, the same wayDisposableStackdoes.
Exercise
A stack registers three things in this order: stack.use(a), stack.defer(async () => log("x")), stack.use(b). Both a and b log their names when disposed. What is printed when the stack is disposed, and does b's cleanup finish before "x" is logged?
Show answer
The output is "b", then "x", then "a". Disposal runs in reverse order of registration, and each step is awaited before the next begins, so b's async cleanup finishes completely before the deferred callback logs "x".
Exercise
Why does openAll in the worked example call stack.move() instead of returning stack directly?
Show answer
The stack is declared with await using, so it is disposed when openAll returns. Returning it directly would hand back resources that are already closed. move() moves the registered cleanup steps to a new stack that the caller owns and leaves the original empty, so its disposal at the end of openAll does nothing.