First, let's simply this example:
function *createGenerator(input) {
yield input
}
var generator = createGenerator('input')
console.log(
generator
.next()
.value
)
// input
So you can pass a value into the generator on creation and pull it out, but if you've already created the generator, the only way to get a value in is by passing it through .next
. But which .next
?
function *createGenerator() {
const input = yield
yield input
}
var generator = createGenerator()
console.log(
generator
.next('input1')
.value
)
// undefined
console.log(
generator
.next('input2')
.value
)
// input2
As you can see in this example, the first input doesn't come through, but the second does. That's because your code executes in a generator up to the first yield
and then stops. Because of that, the first value you pass in will be missing because there's no code to evaluate it.
Let's look at another example:
function *createGenerator() {
const input1 = yield
const input2 = yield input1
yield input2
}
var generator = createGenerator()
console.log(
generator
.next('input0')
.value
)
// undefined
console.log(
generator
.next('input1')
.value
)
// input1
console.log(
generator
.next('input2')
.value
)
// input2
console.log(
generator
.next('input3')
.value
)
// undefined
When you call .next
the second time, you evaluate the value passed in, and keep processing code until the next yield
. In this case, you execute yield input
, but nothing to the left of it because that's technically the "next line" of execution in JavaScript's AST.