Skip to content
jshacks.dev
Async

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.

1 min read
Summarize in AI

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.

JavaScript
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();
Text
running
close db
close cache
close server

defer 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.

Taggednode 24
Share

More snippets

Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.