//

ES6 GENERATORS

ES6 generators are functions that can be paused or resumed, and work cooperatively in a multitasking applications.

ES6 generators become useful in the scenarios listed below:

  • Asynchronous function calls
  • Iterables

Cooperative

Generator function, itself chooses when it will allow an interruption – corporate with other code.

Between Pause and start of a generator, other code can be run.

Stop Start

Generators can add pause-resume kind of capability to your application to avoid blocking calls.

yield

Pauses the function – nothing can pause a generator from outside.

Once yield-paused, a generator can’t resume by itself. External control needed to resume.

Infinite Loops

Generators also use infinite loops to keep it listening for changes, which never finishes.

while(true) { .. }

Even though it’s a bad practise in other scenarios, while loop is ideal for generators.

Parameters

With normal functions, you get parameters at the beginning and a return value at the end.

With generator functions, you send messages out with each yield, and you send messages back in with each restart.

Pause-resume helps 2-way message passing (in and out of the generator).

  • Normal functions – get parameters at the beginning, return a value at the end
  • Generator functions – send messages out with yield, get messages with each restart

Yield expression – when we restart the generator we send a value back in, and that value will be the computed result of that yield.

Syntax

Here is a simple example on how to use generators:

function *foo() {
    yield "bar"; // highlight
}
 
const iter = foo();
const result = iter.next();
console.log(result);  // {"value":"bar","done":false}

Line 2: At pause, bar is sent out.

Line 6: The generator restarts and gives the value back

Line 7: Print out the result {“value”: ”bar”, ”done”: false}

Let’s improve on it a bit:

function *foo() {
    const foobar = yield 'bar';
    console.log(footer);  // foo
}
 
const iter = foo();
console.log(iter.next());
// the generator restarts and gives a value back
console.log(iter.next('foo'));

Line 3: Prints out foo.

Line 6: Prints out {“value”: ”bar”, ”done”: false}

Line 7: Print out the result {“done”:true}

When you run this code snippet, you will get the following results:

{“value”:”bar”,”done”:false}
foo 
{“done”:true}
Babel REPL

In order to run the examples, you need to use the Babel REPL.

Conclusion

ES6 generators can be difficult to grasp first. But once you start using them, you will quickly realise the benefits surrounding it.

If you want to learn more about generators, MDN is a great place to start.