Make it Real Elite — Fourth week — ES6 Generators

One of the biggest benefits in JavaScript ES6 is a function called generator; this let the function pause in the middle of the execution and resume latter, allowing another code rune during this period. To pause the generator function use yield inside the function body; it only can be paused inside the function using yield, nothing can pause it outside the function.

With normal functions, you get parameters at the beginning and return at the end; with this type of functions, you send a message out with each yield and send a message in with each restart.

To use this type of function you must use this syntax

function *foo() {
// ..
}

or

function* foo() {
// ..
}

Both are valid.

When a function is paused, it cannot resume on its own, there must be an external control that will restart the function. To restart a function you can use next(); let’s see an example

function *foo() {
yield ‘hello’;
yield ‘world’;
yield ‘this’;
yield ‘is’;
yield ‘an’;
yield ‘example’;
}

to see the results you can set the function in a var and console.log() it:

var message = foo();
console.log(message.next());
console.log(message.next());
console.log(message.next());
console.log(message.next());
console.log(message.next());
console.log(message.next());
console.log(message.next());

So, the result will be an object with the value that we set after the yield and done which will be a boolean that is going to be true when it ends; the result of the example will be:

{value: “hello”, done: false}
{value: “world”, done: false}
{value: “this”, done: false}
{value: “is”, done: false}
{value: “an”, done: false}
{value: “example”, done: false}
{value: undefined, done: true}