In JS, code runs single-threaded, that's why asynchronicity is necessary. I cannot use code like result = someRequest()
, instead I need to give it a callback someRequest(resultCallback)
or write a Promise result = await someRequest()
.
But why was the language designed like this? Wouldn't it be much simpler if everything was awaited by default? For running functions in parallel (currently e.g. Promise.all(...)
), we would then instead be using WebWorkers or Thread.spawn(()=>{...})
the like. But this in my opinion is easily outweighted by being able to write code like this:
const data = [1,2,3].map(v =>
fetch(v).json())
or
console.log(1)
sleep(1000)
console.log(2)
My point being, whether sleep(1000)
actually suspends the entire thread or whether it is non-blocking, is internal logic and most cases irrelevant to the programmer. Contrary to for example Rust, where you always need to actively decide for or against spawning an extra thread. Why do we need to bother with the special syntax then?
In case I am not missing anything, why is there no common JS preprocessor for this? It would need to prefix everything with await
and rewrite (besides others) all Array processing functions like .map()
.
Thanks!