ES6 Generators and Async/Await
What are ES6 Generators?
How Generator function work?
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?
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 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:
- async/await uses await instead of yield.
- async/await uses an async function as a keyword in their syntax instead of function*.
- 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