Generators

NOTE: You cannot use generators in TypeScript in a meaningful way (the ES5 emitter is in progress). However that will change soon so we still have this chapter.

function * is the syntax used to create a generator function. Calling a generator function returns a generator object. The generator object just follows the iterator interface (i.e. the next, return and throw functions).

There are two key motivations behind generator functions:

Lazy Iterators

Generator functions can be used to create lazy iterators e.g. the following function returns an infinite list of integers on demand:

  1. function* infiniteSequence() {
  2. var i = 0;
  3. while(true) {
  4. yield i++;
  5. }
  6. }
  7. var iterator = infiniteSequence();
  8. while (true) {
  9. console.log(iterator.next()); // { value: xxxx, done: false } forever and ever
  10. }

Of course if the iterator does end, you get the result of { done: true } as demonstrated below:

  1. function* idMaker(){
  2. let index = 0;
  3. while(index < 3)
  4. yield index++;
  5. }
  6. let gen = idMaker();
  7. console.log(gen.next()); // { value: 0, done: false }
  8. console.log(gen.next()); // { value: 1, done: false }
  9. console.log(gen.next()); // { value: 2, done: false }
  10. console.log(gen.next()); // { done: true }

Externally Controlled Execution

This is the part of generators that is truly exciting. It essentially allows a function to pause its execution and pass control (fate) of the remainder of the function execution to the caller.

A generator function does not execute when you call it. It just creates a generator object. Consider the following example along with a sample execution:

  1. function* generator(){
  2. console.log('Execution started');
  3. yield 0;
  4. console.log('Execution resumed');
  5. yield 1;
  6. console.log('Execution resumed');
  7. }
  8. var iterator = generator();
  9. console.log('Starting iteration'); // This will execute before anything in the generator function body executes
  10. console.log(iterator.next()); // { value: 0, done: false }
  11. console.log(iterator.next()); // { value: 1, done: false }
  12. console.log(iterator.next()); // { value: undefined, done: true }

If you run this you get the following output:

  1. $ node outside.js
  2. Starting iteration
  3. Execution started
  4. { value: 0, done: false }
  5. Execution resumed
  6. { value: 1, done: false }
  7. Execution resumed
  8. { value: undefined, done: true }
  • The function only starts execution once next is called on the generator object.
  • The function pauses as soon as a yield statement is encountered.
  • The function resumes when next is called.

So essentially the execution of the generator function is controllable by the generator object.

Our communication using the generator has been mostly one way with the generator returning values for the iterator. One extremely powerful feature of generators in JavaScript is that they allow two way communications!

  • you can control the resulting value of the yield expression using iterator.next(valueToInject)
  • you can throw an exception at the point of the yield expression using iterator.throw(error)

The following example demonstrates iterator.next(valueToInject):

  1. function* generator() {
  2. var bar = yield 'foo';
  3. console.log(bar); // bar!
  4. }
  5. const iterator = generator();
  6. // Start execution till we get first yield value
  7. const foo = iterator.next();
  8. console.log(foo.value); // foo
  9. // Resume execution injecting bar
  10. const nextThing = iterator.next('bar');

The following example demonstrates iterator.throw(error):

  1. function* generator() {
  2. try {
  3. yield 'foo';
  4. }
  5. catch(err) {
  6. console.log(err.message); // bar!
  7. }
  8. }
  9. var iterator = generator();
  10. // Start execution till we get first yield value
  11. var foo = iterator.next();
  12. console.log(foo.value); // foo
  13. // Resume execution throwing an exception 'bar'
  14. var nextThing = iterator.throw(new Error('bar'));

So here is the summary:

  • yield allows a generator function to pause its communication and pass control to an external system
  • the external system can push a value into the generator function body
  • the external system can throw an exception into the generator function body

How is this useful? Jump to the next section async/await and find out.