← back to the blog


What are JavaScript generators, function* generator?

Posted on April 27th, 2020 in JavaScript by George

 

Generators are functions that can be used as an iterator.

Comparing to a standard function, the generator has more capabilities (implementing iterable and iterator protocols);

A basic function can encapsulate code to execute and/or return a value.

A Generator function has the (yield, yield* - this one will delegate another generator) special keywords that return a generator object every time the next() method is called on the generator.

On each next call an object with form

{value: "value", done : false}

is returned.

Example:

// Use a Generator for regular async requests and other synchronous values return

// dummy user object to be  used as a network response
let response = { name: 'George', age: 30, activityList: ['Coding', 'Running'] };

// Our Function Generator

function* exampleGenerator() {

  yield dataRequest();

  yield* [1,'2'];

  yield 'I am done here!';

}


function dataRequest() {
  return new Promise((resolve, reject) => {
    //simulate slow network request
    setTimeout(() => {
      resolve(response);
    }, 1000);
  });
}

let fetchUserData = exampleGenerator();

let firstNext = fetchUserData
  .next().value
  .then((userData) => {
      console.log(userData);
      console.log("Second Next", fetchUserData.next())
      console.log("Third Next", fetchUserData.next())
      console.log("Fourth Next", fetchUserData.next())
      console.log("Fifth Next", fetchUserData.next())
    }
  );

console.log("First Next", firstNext);


let forOfExample = exampleGenerator();

/*
 This is an example of how the generator can be used 
 with and for ..of loop what will run next implicitly
*/
for(let i of forOfExample) {
   //console.log(i);
}

 

 

And the output:

 

➜  jsstuff node generators.js
First Next Promise { <pending> }
{ name: 'George', age: 30, activityList: [ 'Coding', 'Running' ] }
Second Next { value: 1, done: false }
Third Next { value: '2', done: false }
Fourth Next { value: 'I am done here!', done: false }
Fifth Next { value: undefined, done: true }

 

Thank you