Async is a Javascript hack that inexplicably got ported to other languages that didn't need it. The issue arose because Javascript didn't have threads, and processing events from the DOM is naturally event driven. To be fair, it's a rare person who can deal with the concurrency issues threads introduce, but the separate stacks threads provide a huge boon. They allow you to turn event driven code into sequential code.…
What if process_the_character takes multiple seconds waiting on a network request?
while (char = read())
process_the_character(char);
It may look more like this: element.onkeydown = window.greenThread(processKeyEvents, ...);
...
function processKeyEvents(green_thread, ...) {
while (event = green_thread.yield(...)) {
/* process the key event */
var foo = call_some_function_that_blocks(...);
/* more processing */
}
}
You can only call a function that blocks (like `green_thread.yield()`) from within a green thread. Attempt it outside of a green thread and they throw an exception.Code is effectively still coloured, because a call that can block can't be called from a context that doesn't allow block (like DOM events). async makes this colouring obvious but it comes at the expense of new keywords, new concepts like promises and futures, and manually creating the stack using linked object on the heap. A real stack is far faster than allocating stuff on the heap. But to repeat the key observation above: async and green threads are semantically near identical, it is only the implementation is different.
One selling point used for async is it makes blocking calls obvious, and that would somehow avoid bugs. The claim (willfully?) ignored that green threads (aka, cooperative multiasking) were the earliest form of multitasking - they have been around for over 50 years at this point. They were never a source of the sort of bugs they claimed would happen.