Actually, the relevant paragraph is a little below in https://developer.mozilla.org/En/New_in_JavaScript_1.7:
Once a generator has been started by calling its next()
method, you
can use send()
, passing a specific value that will be treated as the
result of the last yield
. The generator will then return the operand
of the subsequent yield
.
I think that this is only relevant if the generator is used by calling its methods directly, not when looping over its values - a loop will always call next()
on the generator and never send()
.
In a way, generator execution is similar to cooperative multitasking. The generator executes until the yield
statement is found. It returns control to whoever called next()
or send()
on the generator. The caller then continues executing, until the next next()
or send()
call is performed - now the generator is executing again. Each time values can be passed back and forth.
Here a simple example:
function gen()
{
var [foo, bar] = yield 1;
console.log("Generator got: " + foo + ", " + bar);
}
// This creates a generator but doesn't run it yet
var g = gen();
// Starts generator execution until a yield statement returns a value
var result = g.next()
console.log("Received from generator: " + result);
// Continue generator execution with [2, 3] being the return value
// of the yield statement. This will throw StopIteration because the
// iterator doesn't have any more yield statements.
g.send([2, 3]);