Javascript - Generator

About

A generator is a function implementation of an iterator pattern.

When instantiated, you can get the next value with the next().value statement.

Example

Sequence Generator

// A function becomes a generator function with the *
function* seqGen() {
  let i = 0;
  while (true) {
    yield ++i;
  }
}
gen = seqGen();

console.log(gen.next().value); // 1
console.log(gen.next().value); // 2

Async iterator

with a promise

// A function becomes a generator function with the *
function* seqGen() {
  let i = 0;
  while (true) {
    yield new Promise(resolve => { resolve(new Date()) });
  }
}
gen = seqGen()

// To be able to await the promise
async function example(){
   l = await gen.next().value;
   console.log(l.toString())
}

example();
setTimeout(example,2000);
setTimeout(example,3000);

Documentation / Reference


Powered by ComboStrap