await using Awaits Asynchronous Cleanup

await using calls Symbol.asyncDispose when the block exits and awaits the cleanup, so locks and handles release even when the work in between throws.

JavascriptResilience

Code

javascriptsnippet
31 lines
// Symbol.asyncDispose marks an object as an awaitable resource: `await using`
// calls it when the block exits and awaits the cleanup
const lock = {
  acquired: false,
  async [Symbol.asyncDispose]() {
    this.acquired = false;
    console.log('lock released');
  },
};

async function criticalSection(work) {
  await using handle = lock;
  lock.acquired = true;
  console.log('lock acquired:', handle.acquired);
  if (work === 'fail') {
    throw new Error('work failed while holding the lock');
  }
  return 'work done';
}

(async () => {
  console.log(await criticalSection('ok'));

  // Even a thrown error unwinds the resource before the exception propagates
  try {
    await criticalSection('fail');
  } catch (err) {
    console.log('caught:', err.message);
  }
  console.log('lock free again:', lock.acquired === false);
})();

Output

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

lock acquired: true
lock released
work done
lock acquired: true
lock released
caught: work failed while holding the lock
lock free again: true

How the snippet works

criticalSection is the sole function, and the await using handle line inside it owns the cleanup story.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Invalid states are rejected up front: it throws Error instead of continuing with bad data.

Watch out for

  • The environment needs no preparation beyond having the interpreter or compiler.
  • The guard work === 'fail' short-circuits the flow with an early throw when its condition holds.

Applying it

The callable shape is async function criticalSection(work)

Each run prints the 4 labeled blocks lock released, lock acquired:, caught:, lock free again: in source order.

Statements doing the real work

throw new Error('work failed while holding the lock');
await criticalSection('fail');
await using handle = lock;

Interactive Tools for This Topic

FAQ

What happens on invalid input?
The code refuses to continue: `Error` is thrown while the state is still recoverable.
Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `criticalSection` at load time.