Sub topic 6
Asynchronous Cleanup with await using
This chapter assumes you know how async/await and promises work, and that you have read the earlier chapters on Symbol.asyncDispose and the plain using declaration. Here, await using carries the same scope-bound cleanup over to resources whose cleanup returns a promise.
The working model
A plain using calls [Symbol.dispose]() and moves on without waiting. That breaks for resources like database connections, file handles, or network streams, because closing them takes time. An await using declaration calls [Symbol.asyncDispose]() when the block exits and awaits the promise it returns before control leaves the block.
class Connection {
#open = true;
static async connect(url) {
return new Connection();
}
async query(sql) {
if (!this.#open) throw new Error("connection closed");
return [];
}
async [Symbol.asyncDispose]() {
if (!this.#open) return;
this.#open = false;
await new Promise((resolve) => setTimeout(resolve, 10));
console.log("connection closed");
}
}
async function main() {
await using conn = await Connection.connect("db://example");
await conn.query("SELECT 1");
console.log("query done");
} // cleanup is awaited here
await main();
console.log("main finished");
// query done
// connection closed
// main finished"main finished" prints after "connection closed" because the promise returned by main() does not settle until disposal has finished. That stays true when the block exits through return or throw.
The early return in asyncDispose makes disposal idempotent, meaning a second call does nothing. Code that closes the connection manually and then lets await using close it again stays safe.
Two awaits, two jobs
The line await using conn = await Connection.connect(...) contains two awaits, and each one does a different job:
| Keyword | Runs when | Purpose |
|---|---|---|
| `await` before `Connection.connect` | At declaration | Unwraps the promise to get the resource |
| `await using` | At block exit | Awaits the disposal promise |
await using does not await its initializer.
Fallback to Symbol.dispose
If the value has no [Symbol.asyncDispose] method, await using falls back to [Symbol.dispose]. The sync method is still called at block exit, and its completion is still awaited. You can therefore use await using with any disposable. The reverse does not work: a plain using on an object that has only [Symbol.asyncDispose] throws a TypeError at the declaration.
Mixing using and await using
One block can hold both kinds of declaration. Disposal still runs in reverse declaration order, and each async disposal finishes before the next one starts:
async function run() {
using a = { [Symbol.dispose]() { console.log("dispose a (sync)"); } };
await using b = {
async [Symbol.asyncDispose]() {
await new Promise((r) => setTimeout(r, 10));
console.log("dispose b (async)");
},
};
console.log("work");
}
await run();
// work
// dispose b (async)
// dispose a (sync)Common errors
- Forgetting the initializer's
await.await using conn = Connection.connect(url)binds a Promise. A Promise has no dispose method, so this throws aTypeError. - Using
await usingoutside an async context. The declaration is only allowed in places whereawaitis valid: async functions, async generators, and module top level. Anywhere else it is aSyntaxError. - Using
usingwith an async-only resource. As described above, this throws aTypeErrorat the declaration. Switch toawait using. - Assuming concurrency. Disposals run one after another, never in parallel. If you have many slow resources, cleanup time adds up.
Exercise
In an async function, you write using x = makeX(); and then await using y = makeY();. x has only Symbol.dispose, and y has only Symbol.asyncDispose, which takes 50 ms. In what order are they cleaned up, and does x's dispose start before y's promise resolves?
Show answer
y is disposed first and x second, because disposal runs in reverse declaration order. x's dispose does not start until y's 50 ms promise has resolved, since each await using disposal is awaited before the next disposal runs.
Exercise
Why does await using conn = Connection.connect(url); (with no await before Connection.connect) throw?
Show answer
Without the inner await, conn is bound to a Promise, and a Promise has neither Symbol.asyncDispose nor Symbol.dispose, so the declaration throws a TypeError. await using awaits only the disposal at block exit, never the initializer.