To get started, you’ll need Node v0.11.2 or greater. You can easily install this by using the very awesome nvm node version manager. As these are not yet finalized in the ES6 spec their usage is experimental and subject to change and you will therefore need to invoke node with the
--harmony flag. e.g.
node --harmony app.js
Now, a few definitions from MDN:
“A generator is a special type of function that works as a factory for iterators. A function becomes a generator if it contains one or more yield expressions.”
Consider the following generator function
range – we know it’s a generator given the
function* syntax. This will generate all integers from 0 to the specified maximum. Unlike a traditional function which would build the entire array in memory before returning it, our generator yields each value in turn, pausing execution after each
yield (but maintaining state) and resuming execution upon successive
next() calls to the generator.
1 2 3 4 5
Note that instead of a value, generator methods return an object with the properties
value – the value returned by yield – and
done – a boolean indicating if the generator is finished. Let’s see this in action.
1 2 3 4 5 6 7
for...of statement provides a handy shortcut to the value and will take care of terminating the loop once the generator is done.
1 2 3
One last thing you should know is that as well as yielding values, generators are also able to receive values when
next() is invoked with a parameter. This will be returned as the value of the last yield and will resume execution until the next yield is executed. Let’s modify our range function so that passing a flag of
true will reset the generator.
1 2 3 4 5 6 7 8
1 2 3 4 5
For sake of simplicity, let’s assume we wanted the ability to “pause” execution at multiple points during function execution. Consider the following code:
1 2 3 4 5
In the implementation below,
sleep takes a generator, invokes it and passes it to the
nap function. In effect
nap acts as a controller using the
next() method to execute code inside the generator, suspend execution, receives the sleep time from the yield and finally resume execution by calling
1 2 3 4 5 6 7 8 9 10 11 12
I’d also recommend the following posts, all of which provided invaluable information for getting me started:
- How yield will transform Node.js
Mark (mark at payperks dot com) is the Director of Engineering at PayPerks.