Node.js does have Node.js
worker_threads
however.async
is all present in JavaScript for two reasons:- you make network requests all the time
- JavaScript is single threaded, so if you are waiting for a network request, the UI freezes, see remarks on the deprecation of synchronous HTTP request at: developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
However, it is also Hell: how to convert
async
to sync in JavaScript.God, it's impossible! You just have to convert the entire fucking call stack all the way up to async functions. It could mean refactoring hundreds of functions.
To be fair, there is a logic to this, if you put yourself within the crappiness of the JavaScript threading model. And Python is not that much better with its Global Interpreter Lock.
The problem is that async was introduced relatively late, previously we just had to use infinitely deep callback trees, which was worse:compared to the new infinitely more readable:But now we are in an endless period of transition between both worlds.
myAsync().then(ret => myAsync2(ret).then(ret2 => myAsync3(re3)))
ret = await myAsync()
ret2 = await myAsync2(ret)
ret3 = await myAsync3(ret3)
It is also worth mentioning that callbacks are still inescapable if you really want to fan out into a non-linear dependency graph, usually with
Promise.all
:await Promise.all([
myAsync(1).then(ret => myAsync2(ret)),
myAsync(2).then(ret => myAsync2(ret)),
])
Bibliography:
- stackoverflow.com/questions/21819858/how-to-wrap-async-function-calls-into-a-sync-function-in-node-js-or-javascript
- stackoverflow.com/questions/9121902/call-an-asynchronous-javascript-function-synchronously
- stackoverflow.com/questions/47227550/using-await-inside-non-async-function
- stackoverflow.com/questions/43832490/is-it-possible-to-use-await-without-async-in-js
- stackoverflow.com/questions/6921895/synchronous-delay-in-code-execution
And then, after many many hours of this work, you might notice that the new code is way, way way slower than before, because making small functions
async
has a large performance impact: madelinemiller.dev/blog/javascript-promise-overhead/. Real world case with a 4x slowdown: github.com/ourbigbook/ourbigbook/tree/async-slow.Anyways, since you Googled here, you might as well learn the standard pattern to convert callbacks functions into async functions using a promise: stackoverflow.com/questions/4708787/get-password-from-input-using-node-js/71868483#71868483
Articles by others on the same topic
There are currently no matching articles.