demo · v131

await using - async resource disposal

await using binds a resource and guarantees its async [Symbol.asyncDispose] runs at scope exit, even on a thrown error. Run the scenarios and watch the log: the async disposer always fires, multiple disposers unwind in LIFO order, and body-plus-disposer failures surface as SuppressedError.

without await using (manual try/finally)

with await using (auto dispose)

the api

function openDb() {
  return {
    query: async () => "data",
    [Symbol.asyncDispose]: async () => { await close(); }
  };
}

async function run() {
  await using db = openDb();   // disposes at scope exit
  const rows = await db.query();
}

// Multiple resources dispose newest-first.
await using first = openResource("first");
await using second = openResource("second");

// If the body and disposer both fail, the result is SuppressedError.
await using failing = openResource("dispose also fails");
throw new Error("body failed");

see also