Es6 - Generators (Basics)

Writing Javascript has become much more simpler and intuitive ever since it has been standardized. Javascript supports both synchronous/asynchrnous programming. Asynchronous programming is harder for many of us to wrap our head around. In order to make the asynchronous code easier to read and write, the concept of Generators and Iterators is introduced.

While Generators and Iterators are separate entities but the former is more intimidating as a concept.

Concept Building

Generators (in a very basic sense) are functions that can be paused/stopped during their execution.

Normally a function is executed until it executes its body of statements or returns a value. In the case of Generator function, the function execution goes through a cycle of yield, stop and, end.

Creating and Consuming Generators

A Generator function is constructed like below:

function *functionName or function* functionName.

The following piece of code shows how to create Generators and consume them.

function* GeneratorFunction(i){
  yield i;
  yield i+1;
}

const generatorObj = GeneratorFunction(1);

console.log(generatorObj.next()); //{value: 1, done: false};
console.log(generatorObj.next()); //{value: 2, done: false};
console.log(generatorObj.next()); //{value: undefined, done: true};

Each time a yield is encountered, the Generator function returns an object containing the value and the done status. When the status of the object is true, it means we can't yield the value out of the Generator object. (NOTE: If we use return statement in the body of Generator function, it will make the Generator function finished, i.e., it will set the done status to true and return undefined immediately).

Why Generators?

Generators is a powerful tool which when combined with promises helps to write asynchronous code in an easier fashion. Also by using Generators, we can write a custom function throttle.

Conclusion

This article was a brief summary of what Generators are and how to use them. In other follow up articles I will try to write about how to use Generators to their full potential and will also cover some advanced patterns with Generators.