O W ? • Yes! • An engineer formerly of Facebook and currently of Meteor named Benjamin Newman emulated generator behavior using ES5, giving us the opportunity to use it now! • Babel uses Regenerator under the hood to give generator support. If you’re not using Babel now, you really should. Babel is a JS preprocessor that allows you to process ES6 files into ES5 compatible files. • iojs works out of the box with no preprocessing.
S A G E N E R AT O R ? • A generator is a function that returns a generator object. This object is an iterable; that is, you can iterate over it. • Generators can generate output, process input, or both; however I would suggest where possible to either process input or generate output. It simplifies things a lot. • Let’s look at a few examples.
S O B S E R V E R S • Think of a function you can call a bunch of times with different parameters and preserve the state between calls. • Can be done other ways but a large point of generators to simplify code and make it look more synchronous despite being asynchronous.
O S O M E T H I N G C O O L • Ideal for situations where you can receive input multiple times at asynchronous intervals. • Conducive to reactive (ie RxJS, Bacon, etc) programming. • Awesome for WebSockets / polling
S C O - R O U T I N E S • As I was saying earlier, I prefer to take generators and compose them into either data producing or data consuming, not both. • Seeing a generator both produce and consume takes the advantage of generators away for me: simplifying asynchronous code.
R E T U R N ( ) , T RY, C AT C H , A N D F I N A L LY • Calling `.return()` (instead of `.next()`) executes a return at where ever your generator is paused. This can be useful if you need to terminate your generator. • Calling `.throw()` is similar: it throws an error there and allows you to deal with it using a `catch` statement. • `finally` statements are interesting because if you `.return()` you can clean up your generator by putting code into a finally block. • `.return()` doesn’t work out-of-the-box with iojs.
by making your async code look synchronous. • Generators can accept input, give output, or both. • Generators can be used to model things like observables, iterables, csp, lazily evaluated infinite arrays, and much more fun stuff. • Use generators. They give you power.