ES6 Generators and Async/Await

Photo by rawpixel on Unsplash

What are ES6 Generators?

Generator is a function which is totally different from the other normal function, One of the most powerful and exciting new feature coming in Javascript ES6. The aim of this article is to explain, how they work and why are they so powerful.

How Generator function work?

As we all know that the Function in Javascript is ‘run to completion’, it means once the function starts running, it will always run to completion before any other JS code can run. but here the generator function can be suspended in the middle of the function, and that is the most powerful feature for asynchronous programming. it can be play…paused and resume according to you.

Play...Paused…Resume

The execution of this type of function is in your hand, you can run this function whenever you need, you can stop and resume later, allowing other code to run during this paused period.

The generator function contains a yield keyword, to pause the function from inside itself. Nothing can pause a generator function from the outside; it pauses itself when it comes across a yield keyword. So normal function run until it found a return, while Generator function run until it found a yield. and once it called, it returns the Generator Object, which holds the entire Generator Iterable that can be iterated using next() method or for…of loop. let see how it happens…what's the reason behind this play pause thing?

If you are familiar with the basics of javascript, you might know about Closure, if no, then this is a good example to understand the closure as well. take a look.

In javascript, a closure gives you access to an outer function’s scope from an inner function. The inner function will have access to the variables in the outer function scope, even after the outer function has returned. and this is what the schene behind the hidden power of generator function. so there is nothing new.

The syntax of generator function is similar to the normal function except the (*) followed by the name of the function.

On every next() call, the function will resume from where it paused last time. and the concept is, there must be an outer variable which is tracking the function that where it currently execute. same as we saw in the above example, and it updates the value after every next call. and this is how the ES6 Generator works.

Async/Await

Async functions are asynchronous in nature, which always return a promise. and awaits are the keyword inside the async function which is executed after the promise is being resolved. They are similar to the Generator function, the main differences between them are:

  1. async/await uses await instead of yield.
  2. async/await uses an async function as a keyword in their syntax instead of function*.
  3. awaits only works with promises.

so, we can say that async/await is a subset of Generators or we can say:

Async/Await = Generators + Promises