Sub topic 10
Per-Iteration Resources with for (using ... of ...)
This chapter assumes you already know how using and await using declarations work in a block. That includes reverse-order disposal, how null and undefined are handled, and the general syntax rules. It also assumes you know how for...of drives an iterator, including the fact that leaving a loop early calls the iterator's return() method. The examples run in runtimes with native explicit resource management, such as Node.js 24 or later and recent Chromium-based browsers.
Loops often handle a series of short-lived resources: one file handle per path, one database cursor per batch, or one lock per job. Each resource should be released before the next one is acquired. A using declaration in the head of a for...of loop does exactly this. Each value is bound for one iteration and disposed when that iteration ends.
The Basic Form
Put using where you would normally write const:
function makeTemp(i) {
console.log(`create ${i}`);
return {
i,
[Symbol.dispose]() {
console.log(`dispose ${i}`);
},
};
}
function* temps(n) {
for (let i = 1; i <= n; i++) yield makeTemp(i);
}
for (using temp of temps(3)) {
console.log(`use ${temp.i}`);
}
// create 1
// use 1
// dispose 1
// create 2
// use 2
// dispose 2
// create 3
// use 3
// dispose 3Each iteration gets a fresh binding, and each binding owns the value it holds. Disposal happens at the end of the iteration body, before the loop asks the iterator for the next value. At most one resource is alive at any moment.
The binding behaves like const. Assigning temp = other inside the body is a TypeError at runtime, so a resource cannot be swapped out from under the disposal logic.
The mental desugaring
The loop above behaves almost the same as this version:
for (const value of temps(3)) {
using temp = value;
console.log(`use ${temp.i}`);
}In both versions, the per-iteration scope of the loop body is the block that the resource is tied to. Writing using in the loop head is shorter, and it makes the ownership visible on the line where the value enters your code.
Early Exits: break, continue, return, and throw
Disposal runs however the iteration ends. Ordering matters here. The current value is disposed first, and only after that does the loop close the iterator.
function makeTemp(i) {
console.log(`create ${i}`);
return { i, [Symbol.dispose]() { console.log(`dispose ${i}`); } };
}
function* temps(n) {
try {
for (let i = 1; i <= n; i++) yield makeTemp(i);
} finally {
console.log("iterator closed");
}
}
for (using temp of temps(5)) {
if (temp.i === 2) continue;
console.log(`use ${temp.i}`);
if (temp.i === 3) break;
}
// create 1
// use 1
// dispose 1
// create 2
// dispose 2
// create 3
// use 3
// dispose 3
// iterator closedThe continue on iteration 2 still disposes resource 2. The break on iteration 3 disposes resource 3, and then calls the generator's return(), which runs its finally block. Resources 4 and 5 are never created, because the generator stopped before reaching them.
An exception follows the same path:
try {
for (using temp of temps(5)) {
if (temp.i === 2) throw new Error("boom");
}
} catch (e) {
console.log(`caught ${e.message}`);
}
// create 1
// dispose 1
// create 2
// dispose 2
// iterator closed
// caught boomIf dispose 2 had also thrown, the catch block would receive a SuppressedError wrapping both errors. This is the same rule as for a plain block.
The Eager-Collection Trap
The loop only owns the value it is currently holding. Values that the iterator has not handed over yet belong to no one. This becomes a problem when the resources already exist before the loop starts:
function makeTemp(i) {
console.log(`create ${i}`);
return { i, [Symbol.dispose]() { console.log(`dispose ${i}`); } };
}
const all = [makeTemp(1), makeTemp(2), makeTemp(3)];
try {
for (using temp of all) {
if (temp.i === 1) throw new Error("boom");
}
} catch {
console.log("loop failed");
}
// create 1
// create 2
// create 3
// dispose 1
// loop failedResources 2 and 3 were opened but never disposed. A break has the same effect. The loop releases what it has seen and leaves the rest alone.
The two fixes depend on where the resources come from:
- Create lazily. Use a generator, or a
mapover an iterator helper, so that each resource is acquired only when the loop asks for it. If the loop stops early, the later resources never exist. - Own the whole group. If the resources must exist up front, for example because they were opened in parallel, register them all with a
DisposableStackand iterate with plainconst. The stack then guarantees that every resource gets cleaned up, however the loop ends.
Invalid Values in the Loop Head
Values are checked as each one is bound, using the same rules as a using declaration. null and undefined are accepted and skipped at disposal. Any other value without a callable Symbol.dispose throws a TypeError. That TypeError counts as an abrupt exit, so the iterator is closed.
function makeTemp(i) {
console.log(`create ${i}`);
return { i, [Symbol.dispose]() { console.log(`dispose ${i}`); } };
}
function* mixed() {
try {
yield makeTemp(1);
yield null;
yield { i: 3 }; // not disposable
yield makeTemp(4);
} finally {
console.log("iterator closed");
}
}
try {
for (using temp of mixed()) {
console.log(`use ${temp?.i}`);
}
} catch (e) {
console.log(e.constructor.name);
}
// create 1
// use 1
// dispose 1
// use undefined
// iterator closed
// TypeErrorThe body never runs for the invalid value. This means a type mismatch in the data source shows up as an error right away. It does not show up later as a missing cleanup.
Async Variants
There are two separate questions in an async loop. The first is whether the iteration is async (for await). The second is whether the disposal is async (await using). You can combine them freely, as long as any form containing await is inside an async function or a module's top level.
| Loop head | Iteration | Disposal | Context |
|---|---|---|---|
| `for (using x of it)` | sync iterator | `Symbol.dispose` | anywhere |
| `for (await using x of it)` | sync iterator | awaits `Symbol.asyncDispose`, falls back to `Symbol.dispose` | async only |
| `for await (using x of it)` | async iterator | `Symbol.dispose` | async only |
| `for await (await using x of it)` | async iterator | awaits `Symbol.asyncDispose`, falls back to `Symbol.dispose` | async only |
With await using, the loop awaits the disposal before it requests the next value. So async cleanups never overlap, even when the iterator could produce values faster:
function makeConn(id) {
return {
id,
async [Symbol.asyncDispose]() {
await new Promise((resolve) => setTimeout(resolve, 10));
console.log(`closed ${id}`);
},
};
}
async function* connections(n) {
for (let id = 1; id <= n; id++) {
await new Promise((resolve) => setTimeout(resolve, 5));
yield makeConn(id);
}
}
async function main() {
for await (await using conn of connections(2)) {
console.log(`query on ${conn.id}`);
}
}
main();
// query on 1
// closed 1
// query on 2
// closed 2A common mistake is writing for await (using conn of ...) with an object that only implements Symbol.asyncDispose. A plain using looks only for Symbol.dispose, so every such value throws a TypeError when it is bound. Pick the declaration that matches the kind of cleanup, and pick for or for await to match the kind of iterator.
Forms That Are Not Allowed or Behave Differently
The general restrictions on using still apply in loop heads, and there are a few rules specific to loops:
for (using x in obj)is a SyntaxError. Afor...inloop produces property-name strings, which are never resources.- Destructuring is forbidden.
for (using { a } of it)is a SyntaxError, because the declaration must bind the whole value it is going to dispose. Bind the value, then destructure it inside the body. for (using x = acquire(); cond; step)is allowed, but it is not per-iteration. The value is bound once and disposed when the whole loop exits. Usefor...ofif you want one resource per iteration.
| You want | Write |
|---|---|
| One resource per element, created on demand | `for (using r of lazySource())` |
| One resource shared by the whole loop | `using r = acquire();` before the loop, or a C-style `for (using r = ...; ...)` |
| Many pre-opened resources, all cleaned up | a `DisposableStack` plus `for (const r of list)` |
Ownership Across the Generator Boundary
When a generator yields a disposable, ownership moves to the loop at that moment. The generator must not dispose the value itself, and it must not declare it with using inside its own body. If it did, the generator would dispose the resource when its own scope exited, which can happen while the loop is still using the resource. The generator's try/finally (or a using inside the generator) should guard only what the generator itself keeps, such as the underlying directory handle or connection pool that it pulls items from.
Exercise
A generator yields makeTemp(1), makeTemp(2), makeTemp(3) lazily and logs "iterator closed" in a finally block. The loop is for (using t of gen()) { if (t.i === 2) break; console.log("use", t.i); }. List every line logged, in order, assuming makeTemp logs "create N" and its dispose logs "dispose N".
Show answer
create 1, use 1, dispose 1, create 2, dispose 2, iterator closed. The break disposes resource 2 first and then closes the iterator. Resource 3 is never created.
Exercise
You have const handles = await Promise.all(paths.map(openFile)); and then for (await using h of handles) { await process(h); }. Why can this leak, and how would you fix it?
Show answer
All handles are open before the loop starts. If process throws, or the loop breaks, only the handles already reached are disposed, and the rest stay open. Fix it by registering every handle with an AsyncDisposableStack declared with await using as soon as the handles are opened, then iterating with for (const h of handles). Alternatively, open the files lazily from an async generator and use for await (await using h of gen()).
Exercise
Inside an async function, an object has only a Symbol.asyncDispose method. Which of these loop heads accept it without a TypeError: for (using x of it), for (await using x of it), for await (using x of it), for await (await using x of it)?
Show answer
Only the two forms with await using: for (await using x of it) and for await (await using x of it). A plain using requires Symbol.dispose, whether or not the iteration is async.