1

testMultipleLoops2在第一个之后的功能中for awaitl将转向GeneratorStatus:<closed>,我进行了大量研究,但没有找到重新打开它的方法。

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

4

1 回答 1

2

你要求的是不可能的。根据设计(并且根据语言规范),即使您使用 a 提前终止循环,您的变量也会iterator在.lfor .. ofbreak

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

于 2019-03-21T09:22:10.723 回答