1

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}
})()

8
  • 1
    I see 0, 1, 2 ouptut to console - what do you see? what do you expect to see? Commented Mar 21, 2019 at 8:52
  • The expected o/p should like 0,1,2,3,4,5,6,7,8,9,10,11. @JaromandaX Commented Mar 21, 2019 at 9:12
  • 1
    The desired output is 0, 1, 2, ... 11 - the expected output is what you've got. Commented Mar 21, 2019 at 9:12
  • THANK YOU! THANK YOU! THANK YOU! @Alnitak Commented Mar 21, 2019 at 9:15
  • 1
    developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Mar 21, 2019 at 9:21

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

YES! That's the fact I saw, but if I use while(true) and l.next().value
I cant really loop it multiple time. I suspect it can be write in for await style.
Any time you use for on the iterator it's guaranteed that the iterator will no long be usable after that block. That doesn't happen when you use l.next() because you're interacting directly with the iterator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.