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





Discover More
Javascript Function Method
Javascript - Functions

Functions functionalities in Javascript. A function in Javascript is a variable that’s given a reference to the function being declared. The function itself is a value (as an integer or an array) that...
Card Puncher Data Processing
Observable

Cells is the notebook are named and are then variable hosting a function or a value (as javascript does) Cells can be: expressions blocks. { } an object literal ({ }) Example a cell named letters:...



Share this page:
Follow us:
Task Runner