Why couldn't popular JavaScript runtimes handle synchronous-looking asynchronous script?

前端 未结 4 606
鱼传尺愫
鱼传尺愫 2020-11-28 15:39

As cowboy says down in the comments here, we all want to \"write [non-blocking JavaScript] asynchronous code in a style similar to this:

 try 
 {
    var foo         


        
4条回答
  •  时光取名叫无心
    2020-11-28 15:49

    The other answers talked about the problems multi-threading and parallelism introduce. However, I want to address your answer directly.

    Why not? (As in, "why couldn't there be?"... I'm not interested in a history lesson)

    Absolutely no reason. ECMAScript - the JavaScript specification says nothing about concurrency, it does not specify the order code runs in, it does not specify an event loop or events at all and it does not specify anything about blocking or not blocking.

    The way concurrency works in JavaScript is defined by its host environment - in the browser for example that's the DOM and the DOM specifies the semantics of the event loop. "async" functions like setTimeout are only the concern of the DOM and not the JavaScript language.

    Moreover there is nothing that says JavaScript runtimes have to run single threaded and so on. If you have sequential code the order of execution is specified, but there is nothing stopping anyone from embedding the JavaScript language in a multi threaded environment.

提交回复
热议问题