by HumanOstrich · 2y ago · 0 comments
The author shows a plausible way to put these primitives together to create coroutines powering rendering and lifecycles for web components. And although I'm pretty familiar with the syntax involved, I still learned some new ways to put it together from this article.
Also the author's previous intro article to coroutines in JavaScript might be helpful for learning the basic syntax and patterns: https://lorenzofox.dev/posts/coroutine/
There is a lot of very nice functionality in Node around it - pipe functions and the like, and it can work, but in the end I’ve settled on just using async iterators.
It’s just so easy and understandable to go
for await (const item of my AsyncIterator) { … }
And for people who don’t grasp in detail how it all works, the abstraction is very easy to use. const foo = async function() {
const user = await fetchUser()
But if they'd just made a Promise.coroutine, you could equivalently do this without needing to change the language: const foo = co(function* () {
const user = yield fetchUser()
There's some unpopular cases like async iterables or async generators, but for the most part we could've done the same thing without extending the language. I remember the v1 of koa that had yield everywhere and people thought it was confusing af. Then they released with await and suddenly it made sense to people.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.