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}
})()
What you're asking for is impossible. By design (and per the language specification) your
iterator
variablel
is "closed" at the end of thefor .. of
even if you terminate the loop early with abreak
.See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of#Closing_iterators