AsyncDisposableStack Sequences Async Cleanup

Register async teardown hooks with AsyncDisposableStack use, adopt, and defer, then transfer ownership with move so cleanup runs reliably in reverse.

JavascriptResilience

Code

snippet
const trace = [];

function openSession(name) {
  trace.push(`open:${name}`);
  return {
    name,
    async [Symbol.asyncDispose]() {
      await Promise.resolve();
      trace.push(`close:${name}`);
    },
  };
}

async function prepareScopedResources() {
  await using initStack = new AsyncDisposableStack();
  const primary = initStack.use(openSession('db-pool'));
  // Adopt a plain lock token that has no native [Symbol.asyncDispose] method
  const lock = initStack.adopt({ id: 'lock-7' }, async (entry) => {
    await Promise.resolve();
    trace.push(`release:${entry.id}`);
  });
  initStack.defer(async () => {
    await Promise.resolve();
    trace.push('flush:audit-buffer');
  });
  // Transfer ownership out so initStack exits without disposing resources yet
  return { primary, lock, ownership: initStack.move() };
}

async function main() {
  const { primary, lock, ownership } = await prepareScopedResources();
  await using activeStack = ownership;
  console.log('after prepare:', trace.join(' -> '));
  console.log('using:', primary.name, lock.id, 'disposed?', activeStack.disposed);
}

await main();
console.log('after exit   :', trace.join(' -> '));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

after prepare: open:db-pool
using: db-pool lock-7 disposed? false
after exit   : open:db-pool -> flush:audit-buffer -> release:lock-7 -> close:db-pool

Execution walkthrough — AsyncDisposableStack Sequences Async Cleanup

AsyncDisposableStack Sequences Async Cleanup keeps everything in the functions openSession, prepareScopedResources and main.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

The result comes back as an object carrying primary, lock.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Putting it to use

Entry signature: function openSession(name)

The run emits 3 labeled sections — after prepare:, using:, after exit : — one per step.

The entry point wires prepareScopedResources together — run it once and the whole demo flows.

The call returns primary, lock — destructure what you need at the call site.

Core lines

await Promise.resolve();
const { primary, lock, ownership } = await prepareScopedResources();
return { primary, lock, ownership: initStack.move() };

Interactive Tools for This Topic

FAQ

Does `openSession` modify its input?
It does not. Inputs are only read; the return value is freshly built.
What does AsyncDisposableStack Sequences Async Cleanup print when run?
No setup needed: run the file and look for labeled lines like `after prepare:`, `using:`, `after exit :` in the output.