O'Reilly logo

Async JavaScript by Trevor Burnham

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required