3 ms·
What are some use cases of using generators to do coroutines? I honestly can't think of an example that couldn't be handled in a stateful way, by using objects
by baxuz 3y ago
What are some use cases of using generators to do coroutines?
I honestly can't think of an example that couldn't be handled in a stateful way, by using objects/class instances instead of closures.
Even iteration can be handled by implementing [Symbol.iterator] on the instance.
The one place I found a use for them is to syncify async functions in some rare cases where it's needed, as the API would only work with other non-sync functions.
- postalrat 3y agoAlthough it doesn't really matter for much I've found closures to run faster than accessing class properties and found classes to use less memory than closures.
- athanagor2 3y agoHandling user inputs. Each time the generator yields you wait for a user input, and when you receive it you next() the generator with the input. It’s less verbose than using a bunch of methods, or the closest alternative I saw which is a switch/case on the index of the current operation. By using generators you just reuse the standard structures of the language.