Let’s get serious about ES6 generator functions.
Several months have passed since support
for generator
functions and the yield
keyword arrived
in Node.js v0.11.2. This news was
greeted
with
great
excitement,
because generator syntax
provides a
much cleaner alternative to using callbacks when writing
asynchronous server-side code.
One of the biggest benefits of using JavaScript on the server is that you can (in theory at least) run the very same code in a web browser. However, if you choose to use generator functions in Node.js, you end up with a bunch of code that can't be executed client-side. So there's the rub: native support for generators is only so exciting because it enables you to write really clean, powerful, unportable code.
Some of us on the JavaScript Infrastructure team at Facebook got restless waiting for the future to get here, so we developed a tool called regenerator to replace generator functions with efficient JavaScript-of-today (ECMAScript 5 or ES5 for short) that behaves the same way. Since the tool itself is implemented in ES5, you can try it right now, in this web browser, without leaving this web page.
Regenerator relies heavily on the Esprima JavaScript parser and two libraries that we maintain for manipulating abstract syntax trees, ast-types and recast. It is similar in spirit to Google's Traceur Compiler, which supports generators and many other ES6 features through source transformation, but we would argue it compares favorably to Traceur in several ways.
-
Traceur supports
yield
expressions only on the right-hand sides of assignment statements and variable declarations, or as standalone statements, whereas regenerator allows ayield
expression to appear anywhere an expression is permitted to appear. - Regenerator aims to generate as little boilerplate as possible, whereas Traceur generates twice as much code for the simplest of generators.
- Regenerator transforms generator functions and nothing else, so you don't have to buy into the entire Traceur runtime just to get support for generators.
Please give the transformer a try below, and feel free to report bugs. Regenerator is well-tested and feature-complete, but we'd love your help in making it completely bulletproof!