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"​);

Get Async JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.