by rendaw · 6mo ago · 0 comments
All functions, even non-async functions, are colored. In any large system codebase you'll have functions that can only be called in certain situations, with the right setup, whatever, and if you're lucky this is communicated by types but regardless those restrictions can't be avoided. It's easy to call low-restriction functions from high-restriction ones and not the other way around.
Furthermore, it's not like the alternative to explicit await doesn't have issues too (that the article doesn't mention). There is inherent complexity, it's a tradeoff, you can't just syntax it away.
One thing that can be better called out is that this issue of function coloring isn't just an async problem. Exceptions cause function coloring--and not just Java's controversial checked exceptions. An infallible/fallible domain split is function coloring. Javascript's async handling is called out not because it's doing the function coloring but because--in 2015--the tools that existed for dealing with async code in JS libraries were really, really bad, largely reliant on callback hell. Promises and the async/await keyword fix most of the issues, and the ones that aren't fixed boil down to the fundamental issue that an asynchronous event-loop model and a synchronous batch model are just different programming paradigms to begin with.
Some statically typed languages (I believe both Haskell, ocaml) have powerful type system that allow abstracting over function types and function colors. Color is not an issue here.
Some other statically typed languages (C#, rust, and C++ (at least with the built-in stackless coroutines)) can abstract over types but not over colors. This is a problem.
Some statically typed languages (Go) do not encode async-ness statically, so it is not an issue[2].
Some dynamically typed languages (scheme, Lua, lisp) also do not encode async-ness statically. Everything is fine.
Finally there are some dynamically typed languages (python, js) that, eskew static types but for some reason still decide to encode async-ness statically. For me this is the most bizarre decision, especially as some of the justifications for static async-ness (performance, memory usage) are less relevant.
[1] for example, a litmus test is being able to implement an higher order function that inherits its color from one of its parameters. Essentially this is the problem of generically turning an internal iterator to an external one.
[2] fundamentally in these languages continuations are first class values that can be passed around, so the asyncness is naturally not bound to the function that created a continuation.
Edit: you can in principle abstract away color in any async language by simply assuming that any function call is async and await it. Then sync functions can trivially be made async. But at this point async annotations no longer convey any useful property: the language might as well implicitly await any function and require call-site annotations for diverging control flow or reentrancy requirements. More practically as languages with async evolve and grow asyncness becomes pervasive and pushes away any sync component.
Hopefully it's safe read this as there's no common static type between function and async function meaning APIs (that take functions as arguments) have to provide seperate methods (or overloading) for these different colours.
Like in typescript you can write `<T>(f: () => T) => T` because an async function statically is just the return type wrapped in a Promise, not something like `async () => T` you can still pass in an async function as an argument.
I think that's a reasonable thing to take issue with, and its _possibly_ an avoidable design problem. That said I can see it being less avoidable if the async function requires some special kind of invocation (like being associated with some kind of async runtime and its a compiled language).
When I see people bring the issue of function colouring, the focus tends to be on the fact that a function is no longer interchangeable with a sync function and now you have to handle a promise, which I personally find unconvincing if the return type really should be a promise then it shouldn't be interchangeable with a sync function.
An example: a vector of things to a thing of a vector, for "thing" in (promise, option, result<E>, ...). Such a function should only really return a promise if it's given a vector of promises, and, with an interface that "thing" supports, can be written generically for all those things.
(In Rust, there are separate implementations of that for Option and for Future.)
Higher-kinded types are the (a?) design solution, but they _do_ come at a cost, and for some that cost is higher than the cost of colours.
When programming in Node I find in practice async and "colored functions" no issue especially with async await. Except for performance issues they come with sometimes but not at a programming level.
JS solves this problem in two ways in the ecosystem:
- basically saying "all functions must be async" in practice
- allowing you to await a non-awaitable ("await 3" is valid)
so library authors can "force" async/await, but users don't actually have to interact with it when they don't need to. But "everything" being async/await means it's all 'basically fine' anyways
There's also the fact that JS libraries tend to be "pass in a bunch of callbacks" vs, say, Python's "override this class". It makes it much easier for libraries to have everything be async and have it really not get in the way.
Python libs tend to have much larger API surfaces due to how OOP works. So async-y internals works are harder to isolate cleanly without breaking the public API. But if you make your API "async-first" then the debugging experience in Python is miserable (try pdb'ing your way through awaitables....)
Even here though there are problems. For example, I've tried in the past to replace some lib with a more performant WASM-y thing. But it couldn't be a drop in replacement because the original library was a sync-only API, and the replacement was async!
Something very silly: you write "function add(x, y) { return x+y }". A bunch of people do things like "add(add(x, y), z)" everywhere. You find out you could make "add" "better" with async/await. You now have to get all callers to rewrite.
So what everyone does is just throw _everything_ in to the async/await pile. Which... I guess is fine but I personally dislike writing "await add(await add(x,y)), z)".
(aside: Rust's postfix await at least makes this kinda refactor less annoying)
But if you take Python (for example), it's a shitshow. You usually have two versions of the same API, split by function name, client, package, or namespace: `foo` and `afoo`, where the a-prefixed one is async and meant to be used inside async function call chains, and the other one is the blocking version for non-async chains (which are still very much in use). It's a pain to develop for, to maintain, to scale, everything.
Instead, many languages have fibers / coroutines / etc. which simply start new stacks elsewhere, and capture the context.
> Exceptions cause function coloring
do they? Do they?
1) Every function has a color
2) The way you call a function depends on its color
3) You can only call a red function from within another red function
4) Red functions are more painful to call
5) Some core library functions are red
1. It either `throws` or it doesn't
2. If the function `throws` you have to wrap it in try/catch, or make your function `throws`
3. Your function is `red` if it `throws` the same exception.
4. see (2)
5. See the FileReader class in core.
Now, C++ exceptions might not satisfy all of these, but the problems CheckedExceptions were meant to solve still exist in C++ and as a result some style guides forbid them entirely. Like async, the biggest problem with exceptions were the ergonomics.
I know it's not a popular take, but I prefer the idea of Checked Exceptions over unchecked ones [0], and suspect current opinions would be vastly different if Java had shipped with some sweet syntactic sugar for: "If an exception that is of kind A or B or C occurs, automatically throw another checked exception X with the original exception as a cause."
> Ex: If I'm writing a tool to try to analyze and recommend music that has to handle multiple different file types, I might catch an MP3 library's Mp3TagCorruptException and wrap it into my own FileFormatException.
This would reduce the temptation for developers to ruin the type-safety characteristics by wrapping everything in a RuntimeException just to get the ticket out the door.
Checked exceptions are a form of coloring, while unchecked aren't. But Java (which has checked exceptions) has an escape into unchecked land in the form of RuntimeError, most async languages do not, short of spawning a background thread (for sync->async) or force blocking (async->sync).
Interestingly, Result<T,E> based error models are semantically (and even syntactically, mostly, except for the call-site annotation) equivalent to checked exceptions. Usually these languages have enough abstraction capabilities (HKT for example) to make coloring not an issue, or, again, an escape into unchecked land (for example panic in rust or Go, although the latter hardly counts as having Result-like error handling).
To be fair, #3 seems to have shades of grey. In some pls, you can call an async function from a sync one by wrapping it in a whole damn event loop system. Should that count?
> 1) Every function has a color
Every function either throws an exception to indicate failure or doesn't. There's actually several different function colors available here, based on how failure is indicated: throwing exception, aborting the process, composite return value, error code return value, global errno-like variable, error code as a parameter, ....
> 2) The way you call a function depends on its color
See above.
> 3) You can only call a red function from within another red function
Some of the failure methods, like aborting on failure, cannot be converted to another mode at all (or only with very great difficulty). Others, like exceptions and errno-based routines, come with environmental constraints that could be contained by an error conversion routine in theory but may be precluded due to how the system as a whole works (e.g., a global variable errno doesn't play well with threads). Which isn't quite the same thing, but then again, "red function" here is async function, and the call-async-from-sync variant is the easier one to pull off (you spin the event loop), and has roughly the same issues as trying to box an exception routine: it only works if the system as a whole has mechanisms to make it work.
> 4) Red functions are more painful to call
Okay, you've got me here... the exception routines are the easier ones to call, syntactically than non-exception-based ones. Internally in the optimizer, however, exceptions are definitely the worst form (even errno somehow ends up working out better, and that's also deeply problematic).
> 5) Some core library functions are red
Oh yes, standard libraries love using a mix of all of these error-handling routines. Look up C++ <filesystem> for example.
Passing in the context as an argument or making it a global variable or returning a monad doesn't do anything to uncolor the function. What's the difference between `async function f()` and `function f(eventloop, callback)`? Only syntax.
Not to mention there's lots of colors unrelated to async, that most languages don't type at all. And if you use the wrong one, your program just doesn't work correctly at runtime. Thread-safe vs thread-unsafe. Blocking vs non-blocking. May throw/panic vs won't throw/panic. May fail/return null vs infallible.
"Only syntax" is assuming, mistakenly, that syntax doesn't matter.
Also there is a big semantic difference there.. that being in one case you have the flexibility of the passed in parameters taking different forms vs. the static 'async' statement.
It is not strictly an async thing, but a general rule that additional keywords are less powerful than parameters in all cases. Ask any Lisp developer what the difference is..
Negative.
what is the "async prefix" equivalent of the following?
global e: eventloop;
noasync fn parent()
childfn(e)
endRegarding content, I agree with you. Async/Await is an amazing paradigm in JS for simplifying callback patterns and non-blocking suspense.
In other programming languages, there exist other intriguing paradigms that are more elegant and emphasize other aspects of "async"; my prime example 2 would be Erlang, but I am not experienced in, for example, Rust or C#.
The article has the same properties that many successful people IRL have: it makes a certain ick very easy to feel and understand, but it doesn't offer much in terms of profound knowledge.
What it does offer though is a perfect spark of discussion, making people who, for example, only know the single-threaded async-await from JS, consider the sheer possibility of other approaches. I am among those people with a limited horizon, presupposing that "knowing" means deep experience to you.
I have some superficial experience with Java physical threads, also with C#, but $job uses JS/TS.
And even in JS, none of this is trivial in my mind.
Consider the deceptively simple question of a kind of "mutex" that enables an async function or method to control concurrency of its own invocation.
The answer to this simple question (queueing promises and clean rejection handling) is already far from trivial, involves the microtask queue, and shows where the mental model of JS-async-await begins to deteriorate.
I think these APIs address real issues, but it also makes the entire stack more complex when integrated language support might be better for some features. But, keeping things separate does mean JavaScript as a language is fairly portable and backwards-compatible, if you ignore Web API support. Still, a lot of other languages feel more batteries-included and have more elegant multi-threaded async fundamentals.
Didn't want to say that JS cannot provide other paradigms for asynchronous code apart from the async function syntax and Promises.
We've had at least a decade of using these async/await languages and discovered function colouring isn't a problem.
All functions are not coloured, don't try to wriggle out of it by generalising. This article is a specific complaint about Javascript. Javascript is a hack on top of a hack. Its async/await is crap. Javascript requires this "colouring" in a way that C#, Java, Go, Python, Ruby, C, C++, Rust, etc. don't, because they don't have to pretend they're a single-threaded event processing loop, while Javascript does.
The main issue is that sync functions can't call async functions, but in Python, you can bypass that restriction with asyncio.run.
4) Red functions are more painful to call
I guess for me if I reach back to my memory my real problem with asyncio was that it used decorators and wrapping my head around how it was a crazy abuse of generators, completely broke my internal model of how python works (and also how at the time debugging became problematic), and maybe not so much the ergonomics, so strictly speaking a different set of ergonomic problems than in the colored function article
In the case of this article, the metaphor is extremely strong. Colored functions! What could be dumber! You feel like you see the world clearly after reading the article, and you pity the people who can't see the clear categorization of functions like you can! But, in reality, when has this ever annoyed me? Never! I've worked with async functions in JS/TS for over a decade and there hasn't been a single time in my entire life where I've been frustrated or backed into a corner because I wanted to call an async function from a sync one. At worst I've had to tack on "async" to a couple function declarations and be on with my day.
`result = await Promise.all(list.map(f))` is less pleasant to read. And before writing it, I have to think if I want the `f` function to execute concurrently across all entries of the list, or one at a time: `for (const elem of list) { await f2(elem) }`.
Or maybe I should use a library like `p-map` and carefully set the concurrency level. Or maybe I should create a bulk version of `f` that takes an array and is more efficient than calling `f` N times.
And don't get me started when there's `list.forEach(f)` and `f` becomes async, so now it executes concurrently for all elements, and the engineer who made the change didn't realize it.
And then there's Async Generators ...
I'd consider that a positive rather than a negative. That's an important question to think about (usually) and I want the type system to help remind me.
do you have an example in mind when you say this? I think there's some unique messes with async/await (especially when combined with OOP and extension points... either your extension points _all_ have to be async or you have to have awkward restrictions), in a way that, say, permission checks don't have IMO.
a syntax-less "await function" that climbs up the stack trace to whoever is waiting and holds onto the suspension _is_ a way out of the problem the article describes. Requires runtime support but it effectively means you can always suspend.
Not by the analogy laid out in the article.
It made a big fuzz back then but to me it's excellent as a litmus test. Learning async grammar in Javascript takes you an afternoon, after a week it should become familiar. If someone is unable to grasp that ... well, that tells you where they stand.
It is a great article. Just because you misinterpret it doesn’t make it dumb.