JavaScript

JavaScript Generators: Introduction

Generators are a very welcome addition to ECMAScript 6 (ES6). They are called ‘generators’ because they generate values.  A simpler explanation would be that they are functions that have multiple entry and exit points. This seems strange initially as one would think why not just use multiple functions instead of one function overloaded to return values n times.

Simple Example

Output

Note to run this example you need to be running node 0.11 or higher and you have to use the --harmony flag.

Code Review

You can see from the above that a few changes have been added to ES6 to support generators.

First by putting a * after the function keyword (line 1) you can declare that the following function is a generator.  Generators need to created before they can be invoked. This is done above in the call on to generateNumbers() (line 7).

However, once invoked a generator will not run. A call to next() is required and it is this first call to next() (line 9) that causes the code in the generator function to run to the first yield statement (line 2).

The value is retrieved by accessing the value property of the instance of execution of the next() function (line 9). This output is then sent to the console shown in the output section above.

This continues twice more with each time the generator pausing to return a value via the yield keyword and then being restarted by the following call to next().

Other Languages

Other languages have similar constructs, for instance, C# has the async keyword to declare that a method, anonymous method or lamnda expression can await on a long running process.

Coroutines

Generators get a lot more interesting when you wrap them into coroutines.

Categories: JavaScript

Tagged as: ,

Leave a Reply

Your email address will not be published. Required fields are marked *