Javascript - Generator

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > ECMAScript - Grammar Standard

1 - About

A generator is a function implementation of an iterator pattern.

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

Advertising

3 - Example

3.1 - 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

3.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);

4 - Documentation / Reference

web/javascript/es/generator.txt · Last modified: 2019/02/16 17:40 by gerardnico