中断“ for await”循环后如何“重新打开” AsyncIterator?

时间:2019-03-21 08:50:49

标签: javascript async-iterator

在第一个testMultipleLoops2之后的函数for await中, l将变成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}
})()

1 个答案:

答案 0 :(得分:2)

您要的是不可能的。根据设计(以及根据语言规范),即使您以iterator尽早终止循环,您的l变量for .. of也会在break的末尾“关闭”。

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