Added in ES 2016.
keywords - "next", "done"

Uses 'yield' keyword.
This constructors an iterator
This has the ability to pause itself
This code looks synchronous but actually runs asynchronous

Generator Functions

A generator function is an iterator that returns an object that we can call next on.
A generator appears to be a function, but it behaves like an iterator.
A generator function has the ability to suspend and resume execution.

link - 

function* everySingleEvenNumber() { 
  let i = 0;
  while (true) {
    yield i += 2;

var gen = everySingleEvenNumber();

console.log(; // 2
console.log(; // 4
console.log(; // 6
console.log(; // 8

The while (true) construct looks like an infinite loop, but execution is suspended after each yield and only resumed when the iterator next function gets called in the console.log code.
The current value of the local i variable does not reset between each call and is maintained.
Generators differ from async/await, where execution vanishes and only returns when a promise resolves or rejects.

© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext