How to *reopen* AsyncIterator after broke a "for await" loop?

239 Views Asked by At

In the function testMultipleLoops2 after the first for await, l will turn to GeneratorStatus:<closed>, I've done huge research but didn't find a method to reopen it.

const tryRecursive=async function*(i=0){console.count("tryRecursive");yield i++;yield*tryRecursive(i)}
const asyncDelay=(b,delay=1e3)=>new Promise((resolve,reject)=>setTimeout(()=>resolve(b()),delay))
const tryDelayYieldNumbers=async function*(){
  for await(const i of tryRecursive()){
    const result=await asyncDelay(()=>i)
    yield result}}
const testMultipleLoops2=(async()=>{
  const l=tryDelayYieldNumbers()
  let count=3
  for await(const i of l){if(count-->0)console.log(i);else break}
  count=4
  ///But `l` is closed here, can't do future looping
  for await(const i of l){if(count-->0)console.log(i);else break}
  count=5
  for await(const i of l){if(count-->0)console.log(i);else break}
})()

1

There are 1 best solutions below

3
On

What you're asking for is impossible. By design (and per the language specification) your iterator variable l is "closed" at the end of the for .. of even if you terminate the loop early with a break.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of#Closing_iterators