The Future of JavaScript: Generators

The latest iteration of ECMAScript (the specification that all mainstream JavaScript runtimes implement) defines a new JavaScript feature called generators. A generator is a special type of function containing a yield statement. A yield is like a return, except that the generator resumes from that yield statement the next time it’s run.

Conceptually, generators are a little tricky. However, Mozilla’s Task.js (http://taskjs.org/) library shows how they can make async code simpler. Because generators can be resumed, you can write code like this:

 
task.spawn(​function​() {
 
console.log(​"Yielding..."​);
 
yield task.sleep(1000);
 
console.log(​"...resuming 1 second later"​);
 
});

Here’s how this code works: task.spawn runs our generator, which is just a normal function except for the yield. task.sleep returns a Promise (see Chapter 3, Promises and Deferreds) that resolves in 1000ms. task.spawn takes that Promise and attaches our generator as its resolve callback. When the Promise resolves, our generator is called again, resuming after the yield. It may sound complicated, but it works beautifully.

ECMAScript 6 (aka Harmony) hasn’t been finalized yet. Currently, the only major implementation of generators is in the Firefox browser, and they’re enabled only if you specify a JavaScript version of at least 1.7 in your <script> tags, like so:

 
<script​ type=​"application/javascript;version=1.7"​​>

If generators appeal to you, there is a tool that allows you to compile code that uses generators (and other ECMAScript 5+ features) into widely supported JavaScript code: Google’s Traceur.[66]

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.253.88