Generators allow you to write asynchronous code that looks synchronous, and the best part is that it’s easy! You need to wrap your code in a generator function and yield when you want control back from the iterator. We don’t block our main thread this way while waiting for something like AJAX requests or timeouts, which is really important!
✍️ Here’s a simple analogy ✍️
Imagine you are reading an action book, and suddenly your doorbell rings. This is the pizza guy. You get up. However, before you do, you set a bookmark on the last page you read. Once you return, you start the book from the page where you set the bookmark. You don’t start it from scratch. In a sense, you acted as a function of a generator.
👇 How does it Work? 👇
🧵 Calling a generator does not execute the function completely as soon as it’s called. It will return an iterator object that can be used to use the function.
🧵 So this function can be executed part by part, where the yield expression decides these parts.
🧵 To execute these parts, the .next() is used on the iterator. When .next() is called, the function resumes execution until the next yield is found, or the function completes, or a return statement is executed.
🧵 Every time you execute the .next(), the generator returns an object that The value here is the value sent by the yield and the done indicates if the generator has run completely.