Calling a generator does not run its body. It creates an iterator. Call the iterator’s next() method when you want a value: execution runs to the next yield, then suspends without blocking while it waits for another request. Unlike an ordinary function call, the generator can pick up where it stopped. section 6.2 section 6.2.1
Request values and check for completion
function* values() { yield "Katana"; yield "Wakizashi"; } const iterator = values(); iterator.next(); // { value: "Katana", done: false } iterator.next(); // { value: "Wakizashi", done: false } iterator.next(); // { value: undefined, done: true } Each call returns a result object. Check done before treating value as another item; a while loop can keep calling next() until done is true. A for-of loop consumes the values without those manual calls. section 6.2.1
next() can also carry information in the other direction. Once a generator is suspended at yield, an argument to the following next(argument) becomes the value of that entire yield expression. The call both resumes execution and requests the next result. section 6.2.3
Listing 6.8. Sending data to and receiving data from a generator
function* NinjaGenerator(action) { #A
const imposter = yield ("Hattori " + action); #B
assert(imposter === "Hanzo", #C
"The generator has been infiltrated"); #C
yield ("Yoshi (" + imposter + ") " + action);
}
const ninjaIterator = NinjaGenerator("skulk"); #D
const result1 = ninjaIterator.next(); #E
assert(result1.value === "Hattori skulk", "Hattori is skulking"); #E
const result2 = ninjaIterator.next("Hanzo"); #F
assert(result2.value === "Yoshi (Hanzo) skulk", #F
"We have an imposter!"); #F
Follow the two calls: the first obtains “Hattori skulk”; the second sends “Hanzo” into the paused expression and obtains a new result using it. section 6.2.3
This request-by-request behavior is handy for an ID counter: an infinite loop can yield one new ID per next() call while keeping its counter local to the generator. If you only need the produced sequence, for-of is simpler; use next() when you want direct control or need to send a value back. section 6.2.2 section 6.2.1




