Pass value into generator using for of loop

Viewed 172

When iterating over a generator using a for of loop, is there a way to, pass a value back to the generator?

In the following code, when I call iterable.next('some value') manually, I can pass a value back, but the for of loop seems to call the .next() method without any value.

I hope I've explain this in an understandable way.

const test = function* generator() {
  const list = [1, 2, 3, 4]
  for (const x of list) {
    const data = yield x
    console.log(data)
  }
}
const iterable = test()
console.log(iterable.next())
console.log(iterable.next('test2'))

console.log('FOR OF LOOP')
for (const y of iterable) {
  console.log(y)
}
1 Answers

If you want to pass something back in, you need to be in charge of calling next() you can't just delegate it to the for…of.

It's idiomatic to do this with a while loop, but you can also do it with a for loop. For example:

const test = function* generator() {
  const list = [1, 2, 3, 4]
  for (const x of list) {
    const data = yield x
    console.log("passed in value: ", data)
  }
}
const iterable = test()
console.log('FOR OF LOOP')
let message = 0
for (let y = iterable.next(); !y.done; y = iterable.next(++message)) {
  console.log(y.value)
}

Or a while loop:

const test = function* generator() {
  const list = [1, 2, 3, 4]
  for (const x of list) {
    const data = yield x
    console.log("passed in value: ", data)
  }
}

const iterable = test()
let message = iterable.next()
while(!message.done){
  console.log(message.value)
  message = iterable.next("some value")
}

Related