Javascript: Generator functions

What is a generator function?

How does a generator function work?

function normalFunction() {
console.log("I am executing");
var data = 3;
console.log("I am still executing", data);
data = 4;
console.log("I am done executing", data);
}

Generator function:

How to create and use a generator function

function * generatorFunc() {
var value = "value";
console.log("I am starting my execution ", value);
yield "value1";

console.log("I am resuming execution after first pause ", value);
yield "value2";

console.log("I am resuming execution after second pause ", value);
}

const generator = generatorFunction();
console.log(generator.next().value); // I am starting my execution value
// vaule1
console.log(generator.next().value); // I am resuming execution after first pause value
// value2
console.log(generator.next().value); // I am resuming execution after second pause value
// undefined

Uses of generators

Using generators as iterators:

function * loopme() {
yield "One";
yield "Two";
yield "Three";
}

for(const val of loopme()){
console.log(val);
}

// One
// Two
// Three

Async functions:

function foo() {
return new Promise((resolve, reject) => {resolve(3)});
}

foo()
.then((val) => console.log(val))
.catch((err) => console.log(err));
function foo() {
return new Promise((resolve, reject) => {resolve(3)});
}

function *asyncFunc() {
var data = yield foo();
console.log(data);
}
var asyncFuncObj = asyncFunc();
var promiseObj = asyncFuncObj.next().value;

promsieObj
.then((val) => console.log(val))
.catch((err) => console.log(err));

Advantages of generator functions

Lazy evaluation:

function * lazy() {
var x = 2;
var y = yield x;
return y + x;
}

var lazyObj = lazy();
lazyObj.next()
console.log('sum: ', lazyObj.next(3).value);

CODER | BLOGGER | ARTIST | GHOST