MyArchiBook

Archive for May 2017

ES6 Generator functions – A beauty !

leave a comment »

ES6 Generator* function is one of the unique features which helps maintain a flat & clean code.

Example:
Let’s consider a simple example of getting pizza.

Promise based implementation:

generator-promise-based

Generator fn based implementation:

generator-fn

Explanation:

  • Generator fn differentiates itself from other functions by *
    ie., function* pizzaGenerator() or function *pizzaGenerator()
  • runGenerator() can be considered as a util that executes generator function.
  • generator() returns iterator object which exposes next() that helps move to targets in sequence.
  • yield in generator function*() is synonymous to pause. It helps pause the next line execution until the current execution result is obtained (be it function call or promise)

It’s usage has made my code very straight-forward, flat & clean.

References:

Written by thangaveluaishwarya

May 29, 2017 at 12:27 AM