Iterators


Generators

Added in ES 2016.
A Generator Function is a single function that doesn't resolve its body immediately
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 - codeburst.io/understanding-generators-in-es6-javascript-with-examples-6728834016d5 

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

var gen = everySingleEvenNumber();

console.log(gen.next().value); // 2
console.log(gen.next().value); // 4
console.log(gen.next().value); // 6
console.log(gen.next().value); // 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