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.