tc39 / proposal-iterator-sequencing

a TC39 proposal to create iterators by sequencing existing iterators
https://tc39.es/proposal-iterator-sequencing
42 stars 1 forks source link

Close all the arguments #2

Closed bakkot closed 3 months ago

bakkot commented 4 months ago

Consider

async function* concat(a, b) {
  yield* a;
  yield* b;
}
async function* gen(str) {
  try {
    yield str + "1";
    yield str + "2";
    yield str + "3";
  } finally {
    console.log("closed " + str);
  }
}

for await (const chunk of concat(gen("a"), gen("b"))) {
  console.log(chunk);
  if (chunk === "a2") break;
}

// oops, we never closed `b`!

(slightly simplified from here).

I think the behavior of the concat function there is not what we want. concat (or whatever equivalent we go with) is logically "taking ownership" of any iterators passed into it, which means it is responsible for closing them.

Practically, I think that means looking at each of the arguments it hasn't gotten to yet, checking to see if they have a next and return, and calling return if so. This has the downside that something with both a next and a Symbol.iterator which is not just return this will behave differently depending on when exactly concat is closed, since the approach I've outlined will check next first whereas we normally check Symbol.iterator first.

Alternatively we could do GetIteratorFlattenable and then IteratorClose, but that has the downside of opening iterators from iterables which we aren't otherwise touching. I guess the consistency argument is maybe worth that cost? Unclear.