Sub topic 6
Asynchronous Cleanup with await using
Many resources can't be released synchronously. A database connection sends a termination packet and waits for the server's acknowledgment. A file handle flushes buffered writes before it closes. A worker pool waits for running jobs to finish. If the cleanup returns a promise, a plain using declaration calls it and moves on without waiting, so the promise is left floating. The await using declaration covers this case. It calls Symbol.asyncDispose when the block exits and waits for the returned promise to settle before execution continues.
This chapter assumes you know promises and async/await, and that you have read the earlier chapters on Symbol.asyncDispose, disposable objects, and the reverse-order rule for using.
The Shape of an await using Declaration
The syntax mirrors using, with await in front:
class Connection {
#open = true;
static async connect(url) {
// pretend to connect to 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");
} // cleanup is awaited here
main();The declaration line contains two awaits, and they do different jobs:
| Part | What it does | When it runs |
|---|---|---|
| `await Connection.connect(...)` | Waits for the connection promise and produces the `Connection` object | At the declaration |
| `await using conn` | Registers `conn` for asynchronous disposal | Disposal is awaited when the block exits |
The await in await using does not wait for the initializer. It marks that the exit from this scope contains a hidden await. That is why await using is only allowed where await is allowed: inside async functions, inside async generators, and at the top level of ES modules. Using it in a regular function or a classic script is a syntax error.
What Happens at Block Exit
When control leaves a block that contains await using declarations, the runtime does the following:
- It walks the registered resources in reverse order of declaration.
- For each resource, it calls the dispose method it captured when the declaration ran.
- It awaits the result before moving to the next resource.
- After every resource has been handled, control continues by falling through, returning, or rethrowing.
Disposal is sequential. The runtime never disposes two resources in parallel, even when both are async. That is deliberate. A later resource often depends on an earlier one: a transaction depends on its connection, and a writer depends on its file handle. The dependent resource has to finish closing before the thing it depends on starts closing.
The timing below shows this:
// Save as order.mjs and run with: node order.mjs
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const start = Date.now();
const log = (msg) => console.log(`${String(Date.now() - start).padStart(4)}ms ${msg}`);
function asyncResource(name, ms) {
log(`open ${name}`);
return {
name,
async [Symbol.asyncDispose]() {
log(`closing ${name}`);
await sleep(ms);
log(`closed ${name}`);
},
};
}
async function run() {
await using a = asyncResource("a", 50);
await using b = asyncResource("b", 20);
log("work");
return "result";
}
const value = await run();
log(`run() resolved with ${value}`);The output looks roughly like this (exact milliseconds will vary):
0ms open a
0ms open b
0ms work
1ms closing b
22ms closed b
22ms closing a
73ms closed a
73ms run() resolved with resultTwo details are worth noting. First, a doesn't start closing until b has finished, so the total time is the sum of both cleanups. Second, the promise returned by run() doesn't resolve until all cleanup is done. The return expression "result" is evaluated before disposal starts, but the caller receives it only after the last dispose promise settles.
If you need parallel cleanup for resources that really are independent, await using won't provide it. Write one disposer that calls Promise.all over the cleanups, or use the AsyncDisposableStack patterns covered in a later chapter.
Which Method Gets Called
When the await using declaration runs, before your block body, the runtime looks up a dispose method on the value:
- If the value has
Symbol.asyncDispose, that method is used. - Otherwise, if it has
Symbol.dispose, that method is used as a fallback. - If it has neither, a
TypeErroris thrown immediately at the declaration.
Because of the fallback, you can put a synchronous disposable in an await using declaration without writing an adapter. The sync method is called, its return value is ignored, and the block exit still awaits. If the sync method throws, the error is treated like a rejected async disposal.
async function demo() {
await using syncThing = {
[Symbol.dispose]() {
console.log("sync dispose via await using");
return Promise.resolve("ignored");
},
};
console.log("body");
}
await demo();
// body
// sync dispose via await usingThe method is captured once, at declaration time. If you reassign obj[Symbol.asyncDispose] later in the block, the runtime still calls the original method. Declarations are also constant: conn = other inside the block is a TypeError in strict code, the same as with const.
Mixing using and await using
A single block can contain both kinds of declaration. They share one disposal list and follow the same reverse order:
function syncRes(name) {
return { [Symbol.dispose]() { console.log(`sync close ${name}`); } };
}
function asyncRes(name) {
return {
async [Symbol.asyncDispose]() {
await new Promise((r) => setTimeout(r, 10));
console.log(`async close ${name}`);
},
};
}
async function mixed() {
await using conn = asyncRes("conn");
using lock = syncRes("lock");
await using file = asyncRes("file");
console.log("work");
}
await mixed();
// work
// async close file
// sync close lock
// async close connA plain using entry is disposed synchronously when its turn comes. The async entries around it are still awaited. Choose the keyword based on the resource's own cleanup, not on the surrounding code. Mixing them in one block is normal.
Common Errors
Forgetting await on the initializer
This is the most common mistake:
class Conn {
static async connect() { return new Conn(); }
async [Symbol.asyncDispose]() { console.log("closed"); }
}
async function broken() {
try {
await using conn = Conn.connect(); // missing await
console.log("never reached");
} catch (e) {
console.log(e instanceof TypeError); // true
}
}
await broken();Conn.connect() returns a Promise. Promises don't implement Symbol.asyncDispose, so the declaration throws a TypeError. The failure is loud, which helps. It is worse when a factory returns a promise for an object that also happens to be a valid disposable, because then the wrong thing gets registered.
Using await using in a non-async context
function notAsync() {
await using x = something(); // SyntaxError
}The fix is to make the function async, which turns its callers into promise consumers. Alternatively, keep the function synchronous and return the resource so the caller manages it.
A hanging dispose blocks everything
Because disposal is awaited, a dispose method whose promise never settles makes the enclosing async function hang forever. No error appears, and code after the block never runs. Bound slow cleanup with a timeout:
function withTimeout(promise, ms) {
let timer;
return Promise.race([
promise,
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error("dispose timed out")), ms);
}),
]).finally(() => clearTimeout(timer));
}
const flaky = {
async [Symbol.asyncDispose]() {
await withTimeout(new Promise(() => {}), 100); // never settles on its own
},
};
async function guarded() {
await using r = flaky;
}
await guarded().catch((e) => console.log(e.message)); // "dispose timed out"Non-idempotent dispose
The language calls your disposer once per declaration. Your own code, a DisposableStack, or a second owner may call it again, though. The Connection example above guards with if (!this.#open) return;. Do the same in your own disposers. Make the second call a no-op, and if a close is still running, return the same in-flight promise instead of starting another one.
Edge Behaviors Worth Knowing
nullandundefinedare allowed.await using x = null;registers nothing to dispose. The block exit still includes anawait, so the timing of the code that follows stays consistent whether or not the resource was present. A later chapter covers optional resources.- Disposal runs on every exit path. That includes normal completion,
return,break,continue, and thrown exceptions. If the body throws and a disposer also rejects, you get aSuppressedError, which the chapter on cleanup failures covers. - Returning the resource doesn't save it.
return conn;from a block that declaredawait using connhands the caller an already-disposed object. To transfer ownership, don't declare it withusingin that scope, or useDisposableStack.prototype.move. - Top-level await using in modules disposes when the module body finishes evaluating, not when the program ends. It suits scripts that do their work in the module body. It does not suit long-lived module-level singletons.
Exercise
A block declares, in order, await using a (async dispose takes 30ms), using b (sync), and await using c (async dispose takes 10ms). Give the disposal order and roughly how long block exit takes.
Show answer
The order is c, then b, then a, the reverse of declaration. Each async disposal is awaited before the next one starts, so exit takes about 10ms + 0ms + 30ms = 40ms. The cleanups are never run in parallel.
Exercise
Why does await using file = openFile("log.txt"); throw a TypeError when openFile is an async function that resolves to an object with Symbol.asyncDispose?
Show answer
openFile returns a Promise, and the await in await using applies only to disposal, not to the initializer. The runtime checks the Promise itself for Symbol.asyncDispose or Symbol.dispose, finds neither, and throws. Write await using file = await openFile("log.txt");.
Exercise
An object has only a [Symbol.dispose]() method that returns a promise from flushing a buffer. It is declared with await using. Is the flush awaited? What should you change?
Show answer
No. With await using, the fallback calls Symbol.dispose and discards its return value, so the flush promise is not awaited and may finish after the block, or fail without anyone seeing the error. Implement async [Symbol.asyncDispose]() that awaits the flush.