Use an AsyncDisposableStack for many resources
Use an AsyncDisposableStack for many resources in JavaScript: register cleanups with defer and use, and they run in reverse order. Node.js 24.
When a function opens several resources, one await using per resource gets long. An AsyncDisposableStack collects the cleanups and runs them all, last in first out.
const delay = (ms) => new Promise((r) => setTimeout(r, ms));
async function main() {
await using stack = new AsyncDisposableStack();
stack.defer(async () => {
await delay(5);
console.log('close server');
});
stack.defer(() => console.log('close cache'));
stack.use({
async [Symbol.asyncDispose]() {
console.log('close db');
},
});
console.log('running');
}
await main();running
close db
close cache
close serverdefer registers a plain function, and use registers an object that has Symbol.asyncDispose or Symbol.dispose. When the block ends, the stack disposes them in reverse order of registration, which matches how resources depend on each other: the one opened last is closed first. The class is part of the explicit resource management proposal and is in Node.js 24.
If a cleanup throws, the rest still run, and the errors are combined in a SuppressedError. Call stack.move() to take ownership of the cleanups, for example to return them from a constructor.