Sub topic 10
Per-Iteration Resources with for (using ... of ...)
This chapter assumes you already know how using disposes a resource at the end of its block, how disposal order works, and how for...of drives an iterator. Here the scope that ends is a single loop iteration.
The per-iteration scope
You can put a using declaration in the head of a for...of loop. Each value the iterator produces is bound to a fresh constant. That value is disposed when the iteration that bound it ends, before the next value is requested.
function makeTemp(i) {
return { i, [Symbol.dispose]() { console.log(`dispose ${i}`); } };
}
for (using temp of [makeTemp(1), makeTemp(2)]) {
console.log(`use ${temp.i}`);
}
// use 1
// dispose 1
// use 2
// dispose 2The body ends the iteration however it exits. A normal finish, continue, break, return, and a thrown error all trigger disposal of the current value. The binding behaves like const, so you cannot reassign temp inside the body.
Two separate cleanup mechanisms
A for...of loop already performs one kind of cleanup. When you leave the loop early, it calls the iterator's return() method, and that runs any finally blocks in a generator. This is iterator closing, and it has nothing to do with using:
function* lines() {
try {
yield "first";
yield "second";
} finally {
console.log("generator cleaned up");
}
}
for (const line of lines()) {
console.log(line);
break; // for...of calls return(), which runs the finally block
}
// first
// generator cleaned upThe two mechanisms work at different levels:
| Mechanism | What gets cleaned up | When |
|---|---|---|
| Iterator closing | The iterator itself | Early exit from the loop |
| `for (using x of ...)` | Each produced value | End of every iteration |
If you use both, the current value is disposed first. The iterator is closed after that.
The pre-created resources trap
using only disposes values the loop has actually bound. If you build an array of resources up front and then break, the values the loop never reached are never disposed:
function makeTemp(i) {
return { i, [Symbol.dispose]() { console.log(`dispose ${i}`); } };
}
const temps = [makeTemp(1), makeTemp(2), makeTemp(3)];
for (using temp of temps) {
if (temp.i === 2) break;
}
// dispose 1
// dispose 2
// temp 3 is never disposedfunction makeTemp(i) {
return { i, [Symbol.dispose]() { console.log(`dispose ${i}`); } };
}
function* openTemps(n) {
for (let i = 1; i <= n; i++) yield makeTemp(i);
}
for (using temp of openTemps(3)) {
if (temp.i === 2) break;
}
// dispose 1
// dispose 2 (temp 3 was never created)Async variants and syntax limits
Inside an async function or a module, for (await using x of iterable) awaits Symbol.asyncDispose at the end of each iteration. To consume an async iterator as well, combine both forms: for await (await using x of asyncIterable).
Some restrictions apply:
for (using x in obj)is a syntax error. Property keys are strings and cannot be disposable.- Destructuring is not allowed.
for (using { a } of items)is rejected. nullandundefinedvalues are skipped without error. Any other value that has no dispose method throws aTypeErrorwhen it is bound.
Exercise
A loop runs for (using r of [open("a"), open("b"), open("c")]), where open logs "open X" and disposal logs "close X". The body throws on "b". What is logged, and which resource leaks?
Show answer
The output is "open a", "open b", "open c", "close a", "close b", and then the error propagates. Resource "c" leaks. The array created all three resources before the loop started, but the loop never bound "c", so it was never disposed.
Exercise
In a generator-backed loop for (using r of gen()) where the body hits break, which runs first: r's Symbol.dispose or the generator's finally block?
Show answer
r's Symbol.dispose runs first because it ends the iteration. The loop then closes the iterator by calling return(), which runs the generator's finally block.