简体   繁体   English

使用for循环时如何将值传递回生成器函数

[英]How do you pass a value back to generator function when using for of loop

I'm learning about generators and and iterators and I can't figure out, nor find any details on how to pass a value back to a generator object when iterating over the object using a for of loop. 我正在学习有关generator和and迭代器的信息,无法弄清楚,也找不到使用for of循环遍历对象时如何将值传递回生成器对象的任何详细信息。 I'd like to pass the counter value back on each iteration. 我想在每次迭代时将计数器值传回。 How is this possible? 这怎么可能?

function generate(time, id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(`ALERT: ${id}`)
      resolve(`${id} success.`)
    }, time)
  })
}

function* generator() {
  const testA = yield generate(3000, 'A')
  console.log(`Returned: ${testA}`)
  const testB = yield generate(500, 'B')
  console.log(`Returned: ${testB}`)
  const testC = yield generate(300, 'C')
  console.log(`Returned: ${testC}`)
}

async function test() {
  let counter = 1
  const genObj = generator()
  // await genObj.next(counter).value
  // counter += 1
  // await genObj.next(counter).value
  for (x of genObj) {
    console.log('From here.')
    const t = await x
    counter += 1
    console.log(t)
  }
}

test()

By the spec this is not possible as no arguments are passed to the next() method internally when used in iterator loops like for ... of 根据规范,这是不可能的,因为在迭代器循环(如for ... of )中,内部没有参数传递给next()方法for ... of

https://www.ecma-international.org/ecma-262/6.0/#sec-iterator-interface https://www.ecma-international.org/ecma-262/6.0/#sec-iterator-interface

The for-of statement and other common users of Iterators do not pass any arguments, so Iterator objects that expect to be used in such a manner must be prepared to deal with being called with no arguments. for-of语句和Iterators的其他普通用户没有传递任何参数,因此必须准备使用这种方式使用的Iterator对象要处理不带参数的调用。

So in your case you would have to do a loop where you explicitly call next() 因此,在您的情况下,您将必须执行一个循环,在该循环中您显式调用next()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM