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.
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.
> 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.
T fn() throws E, F, G
vs Result<T, E | F | G> // not even Rust lets you do this.Type systems permit either standardization or fragmentation and that's an ecosystem issue. Another example is that a language without a strong consensus on which string type to use will result in a fragmented ecosystem when each library goes its own way.
I don't understand, why would you need to pick a checked exception? It's the dual or mirror of feeling paralyzed over a return-type because there are "too many kinds of Object to choose from."
If you're writing a CrystalBall class with a gaze_deeply() method, you'll probably return your own VisionResult (extends Object) unless it throws your TooCloudedException (extends Exception).
When someone else writes a wrapper or higher-level layer that uses your code, then it'll be up to them to convert or wrap those results and exceptions into something suitable for their level of abstraction.
> Returning a new kind of error is always a local change
One of my axioms here is that return-values and checked-exceptions are two sides of the same architectural type-system coin. While I'm not familiar with Go, that sounds like something that would be a symptom of bad architecture if it occurred for return values.
In other words, suppose all Java methods always returned Object [0]. That would also ensure that a new return type is "always a local change" to the compiler, but I think most developers would be rightly horrified if they came across code that worked that way.
[0] Let's ignore Java primitives for now.
> When someone else writes a wrapper or higher-level layer that uses your code, then it'll be up to them to convert or wrap those results and exceptions into something suitable for their level of abstraction.
Why though? What do you gain other than longer stacktraces with all those wrappers? People always trot out some theoretical notion that a caller is going to catch that framework's different exceptions and handle them differently, but have you ever seen calling code that actually did that?
> In other words, suppose all Java methods always returned Object [0]. That would also ensure that a new return type is "always a local change" to the compiler, but I think most developers would be rightly horrified if they came across code that worked that way.
There are many different kinds of values. There really aren't that many different kinds of error - there's "transient error that you might want to retry", "programmer called the API wrong", and that's about it, most other cases (like bad user input) probably shouldn't be exceptions.
Usually you just want to propagate or log errors, so having a generic error interface is sufficient. It's true that in Java, you can wrap exceptions, but that's extra boilerplate.
(And yes, Go does notoriously have error propagation boilerplate that they should fix, but that isn't a type system problem.)
In Python, you can wrap the call with asyncio.to_thread, in rust with tokio::spawn_blocking.
"Red functions are more painful to call" alludes to async functions. Every await yields back to the event loop, which adds overhead. Making every function red/async adds a performance cost (and makes it harder to reason about race conditions), which is why JavaScript has a mix of blue and red functions.
Other languages can escape the "red functions can only be called by red functions" trap, like Python asyncio.run or Tokio block_on. JavaScript has no such alternative, not even in Node. Therefore, Python and Rust don't have function coloring, but JavaScript does.
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?
You're probably remembering RuntimeExceptions, which are a subgroup [0] that are exempt from "checking" by the compiler, which means it does not require method signatures to declare "I might emit this."
[0] https://docs.oracle.com/en/java/javase/26/docs/api/java.base...
void fn() throws IllegalStateExceptionTo you, a "whole damn event loop system" is too high a price to pay, but try/catch is not. The complexity of exceptions is invisible to you. However there are certain environments (e.g. FFI) where I dont want "the whole damn exception runtime".
> 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?
I think you have to count any extra overhead where you can't just write f(), including try/catch. It's always possible to call whatever kind of function from whatever other kind of function if you put enough effort and hackery in, so if we can't use functions of kind x in functions of kind y as normal "f()" function calls then that has to be what we mean by colouring.
> 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.
Instead, many languages have fibers / coroutines / etc. which simply start new stacks elsewhere, and capture the context.
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.
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.
From what I've read it's due to a general idea that stacks use a lot of memory, which limits how many of them can be spawned. It's only good if it scales to a million concurrent users. A million 16 KiB stacks is over 16 GiB.
Author makes up a lie.
Then lampshades it away with a colorful non sequitur.
---
The alternatives that people praise like golang, have other tradeoffs that are much worse because the async logic is now implicit. Your entire codebase is now a surface area that is at risk of being blocked by waiting on a channel; the the mitigation of this is through responsible use of coroutines, but then you're right back around to extra information about your code that is analogous to colring, except not as explicit as async/await.
If you don’t depend on anything mutable that anyone else can modify then this is mitigated, but that’s a very specific discipline you have to abide by.
The point of goroutines is that they can freely block when needed. It's not like async where you have to be paranoid at every moment about writing blocking code
The downside of goroutines is that you have no control when the goroutine context switches, so naively accessing a global value can lead to race conditions (which the language has no warnings for despite being such a concurrent language), while the same code works fine in JavaScript because context switches don't happen in synchronous code.
In languages like JavaScript, you have to be careful to avoid blocking the event loop, and use something like worker threads for CPU-intensive tasks. Otherwise you will end up with long tail latencies. In Go, the runtime automatically manages this and can suspend and resume long-running goroutines.
> naively accessing a global value can lead to race conditions
Fair point that the language doesn't automatically catch this, but that's what a mutex is for. In return you get actual parallelism that can use all your CPU cores
Like, why can't my sync function await something asynchronous? If it has to lock up the whole thread while that function executes, that's fine because that's how it was going to work anyway 99% of the time
The answer, at least for Python, is that it is an intentional limitation because the alternatives introduce some quite bad trade-offs.
Option 1: your awaited promise goes into the main async event loop. This is bad because it means that your single-threaded sync function now needs to be thread-safe, and so does any sync code that calls your sync function despite it not even knowing that you're doing anything async. This is essentially unworkable without throwing away the option of writing non-thread-safe code.
Option 2: Your awaited promise goes into its own new event loop that only contains sibling and child promises. There's nothing technically stopping someone from doing this[1], but now you've lost a ton of the value of async because you will inevitably end up with a ton of siloed event loops that leave the process idle despite other async tasks existing that could run. Effective async code needs to share an event loop at as high of a level as possible, which means tainting as many methods with async as possible. At that point, you might as well enforce it at the language level and avoid the inevitable pain and fragmentation that comes from other devs across the ecosystem mixing sync and async code.
[1] https://pypi.org/project/nest-asyncio/
As explained by Guido: https://github.com/python/cpython/issues/66435#issuecomment-...
I agree we shouldn't need to `await` everything though. Effects with inference and implicit perform/await is possible
Plus, you probably don't want to lock up the whole thread if you're writing anything more than a quick script, like a web server or a GUI.
This is why asynchronous I/O APIs became prevalent in JavaScript (initially with callbacks, with promises and then async/await syntax added later to make things nicer). Ryan Dahl then realized that this could also be used in a server-side context and would thereby solve the C10K problem, and so Node.js was initially designed with that same discipline (which was later relaxed a little with APIs like fs.readFileSync).
If Brendan Eich had realized in 1995 that this was how things were going to work, perhaps he'd have added green threads and browser events would spawn new ones (and so could block without locking up the page), but that's not the order things happened in.
I like this general approach a lot, it's overall quite nice for Julia's core use case of number crunching, it means you typically make decisions around concurrency at the call sites. Though it does rely heavily on Julia's runtime, and it can be a bit difficult to figure out what's going on under the hood.
That makes it a pleasure to code concurrent stuff for IMHO.
It does have its own similar problems though - does a function return an error? If so you are going to need to plumb the error return through all the callers. Does a function need a context.Context? Ditto.
I guess you can't win them all :-)
Type classes can smooth over some of it but it's not unusual to have to do some plumbing.
Edit: upon rechecking, apparently that's not exactly right, and Erlang designers learned of actors after designing the language, which makes it all the more interesting
I always joke that BEAM wants to be the operating system.
Propagating errors up the stack is not the same, because the top-level function is not developing an error return because of the 10-level-nested function. It is developing one because the function it called has one, and apparently, it needs to return it to its local caller. It's a local consideration. It is true that it may be a recursive local consideration where this was true 10 times, but the reason it is different is that it doesn't have to be that way. It could have been the case that the function 7 layers down handled the error somehow and it stopped propagating up the stack. But at each point, the consideration was local, and as such, amenable to local solutions other than just tossing the error up. If you choose to "correctly" plumb the error through all your functions, well, good on you for apparently being willing to apply good software engineering practices even when it's annoying, but this is just normal day-to-day function activity stuff.
By contrast, in a function coloring situation, if the color is wrong 10 layers down, you must change the calling function. It's a non-local consideration. You don't get to decide not to change it. You can't encapsulate it. You don't get a choice. It pollutes the entire stack, forcibly.
Another way to look at it is, if the function 10 levels down developed what you think is a color, but there is a way for the function 9 levels down to hide the color from the rest of the stack, even via a hack like simply dropping an error you really need or hackily constructing an object of some type to pass in, then it is by definition not a color. A color change can't be stopped by any way of writing an intermediate function. It must be propagated all the way up the stack.
If you don't have this, you don't have "color". Like, some people will say that in their language that maybe there is some way to encapsulate "async". If you can, then you don't have an async color. Although I will say that if your "encapsulation" is basically to run it in a non-concurrent environment, that's really not encapsulation. It isn't really "encapsulation" if you're giving up an entire major feature of the language, because that is something very visible to the rest of the program.
Go's context.Context is similarly not a color. You can always just create a context.Background() and pass that down. If you didn't have any context already in hand, which means you must not care about any of the features context offers, then that is usually a fine thing to do. Context is trivially bypassed if you don't want it. It can be encapsulated within a portion of the stack without "polluting" the rest of the stack like any other function parameter.
The key aspect of color is that it is not optional. It isn't something that you can just decide to ignore and stop passing up, or trivially create a value for passing down to other functions. You have to change the "color". Async is a color in many environments. There aren't really that many colors in programming languages because they are very, very quickly inconvenient and we tend to squeeze them out. (Haskell really sticks out here as a language that is not only capable of creating arbitrary colors, but where this is an explicit tool used by the community rather than a limitation, and they even have ways of combining colors together deliberately.) Statement versus expression distinctions are another one, where a "statement" may not be usable in an "expression", and you'll note how languages have in general erased that one over time because it's really just a cost without much benefit.
> By contrast, in a function coloring situation, if the color is wrong 10 layers down, you must change the calling function. It's a non-local consideration. You don't get to decide not to change it. You can't encapsulate it. You don't get a choice. It pollutes the entire stack, forcibly.
I think this is an interesting perspective, where I would raise a counterpoint. Both result types and async/await are instances of monads (the abstraction which approximates the article's idea of a function color, since you mentioned Haskell, I assume you know this). Just as you can "eliminate" the result type by explicitly handling the success and error cases, you could, theoretically, "eliminate" the async function by blocking on it. Doing so would treat the entire async subprogram, at the top-level function boundary, as synchronous IO, while the async subprogram would still benefit from concurrency internal to the function.
Compare Example #1:
int topLevel() {
return match fallibleSubprogram() {
Ok(()) => 0,
Err(_) => 255,
};
}
Result<(), Err> fallibleSubprogram() {
let x = f()?;
let y = g()?;
return h(x, y);
}
Compare Example #2: int topLevel() {
block_on(asyncSubprogram);
return 0;
}
async void asyncSubprogram() {
let promiseX = f();
let promiseY = g();
let [x, y] = await Promise.all([promiseX, promiseY]);
return await h(x, y);
}
In the above pseudo-code, you have the same program "structure," but the first uses results and the second uses promises. In the latter example, asyncSubprogram() gets called as if it were synchronous, but you still benefit from asynchronicity because f() and g() can execute concurrently within its body.The main difference is that compared to pattern matching on Result types, programming languages typically make it unidiomatic to block on a promise. There are various reasons why this is the case, but my point is that Result types and async/await are more similar than they may initially appear.
* Haskell: pure function and non-pure (IO monads) looks different. * Rust: unsafe functions (or block) requires special markers.
In Rust, unsafe code can call safe code, and safe code can call unsafe code. Calling unsafe code in safe code requires an explicit unsafe block, but that's fairly normal and not a hack to get around function coloring.
A better example could be Rust async, though unlike JavaScript, you have the option to block the thread on an async function in a sync function.
Which is another problem with the article: it doesn't clearly define what counts as having the "color". The problematic dead-end situation exists in JS, but languages with cross-thread communication can work around it.
It is code you need to write, tradeoffs you need to weigh, invariants you need to keep.
fn someFn() -> Result<T, E>
T someFn() throws E
fun someFn(): T | E // Kotlin's proposed error unions
Checked exceptions actually compose a little better when you have a function that can throw multiple types: T someFn() throws E, F, G
This is like a union type of E | F | G. I don't know about Rust, but most languages won't let you do that over generic types like Result<T, E | F | G>.The main problem for Java's checked exceptions is just how boilerplatey they are, especially when you can't handle something. In Java if you need to become "unchecked" or panic you need to:
try {
someFn();
} catch (SomeException ex) {
throw new RuntimeException(ex); // dunno panic
}
Ideally that would just be: someFn()!!!!; // shut up compile panic if this happensPersonally for me it’s not that big of a deal. The thing I want the most is having null in the type system.
It also provides an error interface so sometimes you don’t need the enum, if all the types return that interface.
i.e. as types you don't know about get introduced the compiler won't stop bad things from happening:
catch (Exception ex) {
switch (ex) {
case SomeException1 se1 -> ..
case SomeException2 se2 -> ..
default -> throw new IllegalStateException(ex); // panic
}
}It's true that if you return an open set of things, you'll have to handle cases you didn't explicitly account for.
Related, one of the former React maintainers wrote a primer on algebraic effects that's a good read: https://overreacted.io/algebraic-effects-for-the-rest-of-us/
E.g., if you install IO handlers that are async and call a function that does IO, it's now an async function.
1. async/await is a huge improvement over callbacks.
2. doing asynchronous programming through callbacks has always been a messy hack, primarily coming from languages that couldn't/wouldn't do real concurrency in their runtimes and async/await just papers over it without fixing the fundamental problems
3. threads are a lot more elegant from a language design standpoint and a lot more powerful, but..
4. .. I would much rather fuss with what color my function needs to be than deal with the average concurrency bug that results from threads.
This comes at a cost, namely that of reading five extra characters in a function signature, and I could kind of imagine (truly!) how that gets in the way for some people. There is a cost of writing the five characters as well (and like the author mentions, in a poorly designed codebase, this may have to go down the call stack), but code is read more often than written, so in a sense this is negligible.
Like the dynamic vs static typing debate, I feel like this ultimately boils down to context and personal taste, and some amount of intelligence as well. I'm impressed by the amount of stuff the dynamic typing / non-async crowd is able to keep in their working or long term memory while coding. I don't have that kind of mental bandwidth, sadly.
Having said all that, this argument is disingenuous in that it completely ignores the fact that the async keyword tells you something useful (rather than some made up nonsense like color), and most of the argument basically boils down to "if you ignore the benefits, this syntax has no benefits", and I really don't respect that as an argument.
I do understand though that it can be annoying for library authors, especially those that need to interact with the FS/Network etc.
Async/await is one implementation of cooperative concurrency, where the programmer must explicitly annotate the points where a context switch may occur. However, one can imagine a program transformation that marks every function as async, and makes every function call an await. After making that transformation, the async/await annotations would no longer be necessary. The end result is pre-emptive concurrency, where the runtime may potentially interrupt the active thread at any function call.
To make another analogy, Haskell requires all IO actions to run in the explicit IO monad, while most languages (C, Java, JavaScript, etc.) do not distinguish between "pure" and "impure" functions. Therefore, C, Java, and JavaScript could all be said to implicitly run in the IO monad.
Async IO is also an instance of a monad. In JavaScript, all async functions must run inside the explicit async IO monad, while Go does not distinguish between async and sync functions. Therefore, Go implicitly runs in the async IO monad. This is similar to the aforementioned distinction between cooperative (made explicit to the programmer) and pre-emptive (handled implicitly by the runtime) concurrency.
In fact, Eugenio Moggi, the PL theorist who realized monads could describe programming languages, was not looking for a programmer-facing abstraction. Rather, he was trying to describe the "implicit" monad in a programming language's semantics (such as the IO monad in most programming languages, or the async IO monad in Go).
This is my principle point of disagreement with the OP comment in this thread. Your response is either not meant for me, or is meant to agree with me, but I'm really not sure but you write:
> In the function color analogy, what this means is that all functions are red
and
> while Go does not distinguish between async and sync functions
Which was my point. Go does not have the function color problem (around sync/async) because it does not color its functions that way.
I do think "There are no function colors in Go in the way being discussed," versus "all functions [in Go] are red" are two slightly different ways of formulating the same set of facts, and the distinction between them is insightful, so that was what I wanted to touch upon. Namely, I wanted to point out that there is an "implicit" color within the programming language itself.
In Go, you can choose to either block on a function call or to execute it as a go routine. The function has no "color" in the sense of the article.
If you want to print asynchronously, you can with a `go fmt.Println("Hello")`, or you can block on that print and remove the `go `. There is no color to any function. And the function containing that, it also has no color. It can be called synchronously or spawned as a go routine, Go makes no distinction between the kinds of functions that can be used each way.
In most async/await languages you can run async functions as sync, eg. Tokio's block_on method or C#'s .Result.
Concurrency is usually a mix of goroutines and channels. There is no inherent link between caller and asynchronous callee. You can use goroutines without channels, and channels without goroutines.
You can write "go" to launch any function call in its own goroutine, but you cannot get a return value from it. This isn't valid:
user_is_valid := go validate_user(u)
The idiomatic way you can do that is to use a goroutine and a channel: ch := make(chan bool)
go func() { // runs asynchronously
ch <- validate_user(u) // blocks until it can send
}()
user_is_valid := <-ch // blocks until it can receive
return user_is_valid // ta-da, blue function returning red function result
I don't think it's a boon to have functions "coloured for you" to tell you that they might block. On the other hand, functions that would block tend to accept a Context parameter to let you control what they should do. It's a major indicator that the function's probably going to do something async, but it doesn't have to. let user_is_valid = validate_user(u).await
But you can also pass around future values. It's pretty dang ergonomic, the tradeoff is that it requires more ceremony to block on async functions (and is not even possible in JS). This was considered a potential problem 10 years ago but we've discovered since than that it's not really an issue at all.My point about the colouring is that it's actually nice to have explicit colouring, in go the asynchronicity of functions aren't encoded by the type system but in practice you still handle them differently. You can't just call one of them without passing in things like context, or handling channels without refactoring anyways.
virtual threads (stackful coroutines) in Java is most of the reason why I’m defaulting to it nowadays instead of C#, Rust, etc
We were using WPF, which is C# combined with XAML. I needed to call some async code. First, I tried to call it from synchronous code. That compiled correctly and seemed okay, but then I got vague crashes, and after doing research, I found everyone was like "don't ever call an async function from a sync function" for that exact reason. So instead, I had to change whatever called that to be async, and then whatever called that to be async, and so on. The solution I ended up having to go with was literally changing the code in over a hundred places. This is legacy code that I touch as little as possible, and instead of the one line fix that it felt like it should have been, async turned it into over a hundred small changes throughout the entire project.
I'm not saying there isn't a better approach. I'm pretty new to async/await code as I've been doing asynchronous code through threads my whole programming career. I don't think WPF is a good technology, so maybe some newer tech has solved it better. But what I can say is that this problem was not invented, it is a real problem and it caused a simple change to become a complicated one.
Implicit management of async operations is something I hope I never have to deal with again.
Thanks for my next horror shortfilm plot. Twist: he's the protagonist
asyncio.gather is a lot less code than having to manage a thread pool or something like Celery with all it's underlying infrastructure.
If you're in an ecosystem where a lot of the async boilerplate is free/cheap (ex: FastAPI) then the developer overhead of sprinkling awaits on your I/O bound calls is pretty low IMO.
Unpopular opinion, but combining this with the other "no thanks" sentiments in this subthread is the right answer. Your app is so complicated you need async? Then it's complicated enough that you can benefit from infrastructure. I don't want to watch coworkers try to badly rebuild message queue or scheduling semantics in an application code base. Just use infrastructure that's made by people who know what they are doing. That was problematic in 2015, but in 2026 it's a bit of docker, and it's not just about web/microservices. Very easy for sufficiently complex apps to simply leverage a local sandbox of celery, redis, graphdb's and whatever. Stand-alone is overrated since we don't have to do it anymore.. app devs should get more comfortable working with ensembles like this so they have access to best-in-class solutions.
You don't like infrastructure AND have such a need for performance AND don't want threads or multiprocess? Consider using another language. Async is mostly a solution in search of a problem, and the enduring popularity of TFA goes to show this has been the right conclusion for ~10 years.
Every rich client-side experience in your browser is written using async code in Javascript or Typescript, as is every electron app. Every developer at my company is comfortable with this pattern, and frameworks like FastAPI make this a similarly smooth experience when using Python.
If async was a solution in search of a problem, it wouldn't have been stolen from C# and added to Rust, Python, Kotlin, etc. The engineering effort required to bring this solution to all these languages is immense, so I'm clearly not the only person seeing value in it.
one, two = await asyncio.gather(callOne(), callTwo())
?
with ThreadPoolExecutor() as executor:
one, two = executor.map(lambda f: f(), [callOne, callTwo])
I'm sure you could write a nicer helper function that's more similar to gather as well.If async/await doesn't solve the coloring problem, then neither do threads. Why would you ever need to start a thread to invoke a function when you could just invoke the function directly? Because the function is a red function.
This article is about async/await. The function coloring problem arises when you have async functions. Regular functions can't call async functions. You have to hoist them into async functions in order to do that.
Threads do solve this problem because they are just regular functions being called by other regular functions. They don't require the entire function stack to be `async` in order to work.
It is not. It tries to address async/await part-way through, but it does so without the context of 10 years of successful async/await usage in javascript, the language it's criticizing.
> Threads do solve this problem because they are just regular functions being called by other regular functions. They don't require the entire function stack to be `async` in order to work.
This is fixating on syntax: it would be trivial for all functions to simply be `async` by default and for all calls to an `async` function to automatically `await`. This might "fix" the coloring problem as you describe it but I argue wouldn't meaningfully change anything.
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.