Generators

Generators are functions which can be exited and later re-entered. Useful for long iteration functions, so they can be paused to prevent blocking other functions for too long.

Basic Syntax

  1. function* myGen() { }
  2. // or
  3. function *myGen() { }

Yield

  1. function *three() {
  2. yield 1;
  3. yield 2;
  4. return 3;
  5. }
  6. var geni = three(); // starts the generator but doesn't run it
  7. geni.next(); // runs the function for one iteration. Returns { value: 1, done: false }
  8. geni.next(); // Returns { value: 2, done: false }
  9. geni.next(); // Returns { value: 3, done: true }. This ends the generator.
  10. geni.next(); // Returns { value: undefined, done: true }

Iterating on Generators

It iterates while done = false.

  1. function *foo() {
  2. yield 1;
  3. yield 2;
  4. yield 3;
  5. yield 4;
  6. yield 5;
  7. return 6;
  8. }
  9. for (var v of foo()) {
  10. console.log(v);
  11. }
  12. // Logs 1, 2, 3, 4, 5

Generator with arguments

  1. function *foo(x) {
  2. var y = 2 * (yield (x + 1));
  3. var z = yield (y / 3);
  4. return (x + y + z); // 5 + 24 + 13
  5. }
  6. var genit = foo(5);
  7. console.log(genit.next()); // { value: 6, done: false }
  8. console.log(genit.next(12)); // { value: 8, done: false }
  9. console.log(genit.next(13)); // { value: 42, done: true }