-3

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!

phil294
  • 179

1 Answers1

0

But why was the language designed like this?

Because JavaScript is just the tiny little bit of glue code which sits between your browser and your proper code which runs in a Java applet. There's no need for it to have anything like asynchronous code, because everything it does completes in a fraction of a second.

Now, history didn't work out that way but you if you're asking "why was the language designed like this" you can't ignore what the original purpose of the language was.