MyArchiBook

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:

Advertisements

Written by thangaveluaishwarya

May 29, 2017 at 12:27 AM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: