Javascript 默认是同步(阻塞)还是异步(非阻塞)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16523870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:00:15  来源:igfitidea点击:

Is Javascript synchronous(blocking) or Asynchronous(nonblocking) by default

javascriptnode.jsasynchronouscallbackasynccallback

提问by static void main

I am trying to grasp on Javascript Asynchronous functions and callbacks.

我试图掌握 Javascript 异步函数和回调。

I got stuck on the concept of callback functions, where I am reading on some places: they are use to have sequential execution of code (mostly in context of jquery e.g animate)and some places specially in the context of Nodejs; they are use to have a parallel execution Asynchronous and avoid blocking of code.

我被困在回调函数的概念上,我在一些地方阅读:它们用于顺序执行代码(主要在 jquery 的上下文中,例如动画)和一些地方,特别是在 Nodejs 的上下文中;它们用于并行执行异步并避免代码阻塞。

So can some expert in this topic please shed light on this and clear this fuzz in my mind (examples??). so I could make my mind for the usage of callback function

因此,该主题的某些专家能否阐明这一点并清除我脑海中的模糊(示例??)。所以我可以考虑使用回调函数

or that is solely depends on the place of where you are calling/placing a callback function in your code? .

或者这完全取决于您在代码中调用/放置回调函数的位置?.

Thanks,

谢谢,

P.S: I am scared that this question would be close as subjective but still I could expect concrete answer for this (perhaps some examples)

PS:我害怕这个问题会接近主观,但我仍然可以期待具体的答案(也许是一些例子)

Edit:actually this is the example from internet which makes me ambigous:

编辑:实际上这是来自互联网的例子,这让我模棱两可:

function do_a(){
  // simulate a time consuming function
  setTimeout( function(){
    console.log( '`do_a`: this takes longer than `do_b`' );
  }, 1000 );
}

function do_b(){
  console.log( '`do_b`: this is supposed to come out after `do_a` but it comes out before `do_a`' );
}

do_a();
do_b();

Result

结果

`do_b`: this is supposed to come out after `do_a` but it comes out before `do_a`
`do_a`: this takes longer than `do_b`

when JS is sequential then do_b should always come after do_a according to my understanding.

根据我的理解,当 JS 是连续的时, do_b 应该总是在 do_a 之后。

回答by Dancrumb

The core of JavaScript is largely synchronous, in that functions complete their task fully, before completing. Prior to the advent of AJAX, it was really only setTimeout and setInterval that provided asynchronous behavior.

JavaScript 的核心在很大程度上是同步的,因为函数在完成之前完全完成了它们的任务。在 AJAX 出现之前,实际上只有 setTimeout 和 setInterval 提供了异步行为。

However, it's easy to forget that event handlers are, effectively async code. Attaching a handler does not invoke the handler code and that code isn't executed until some unknowable time in the future.

但是,很容易忘记事件处理程序实际上是异步代码。附加处理程序不会调用处理程序代码,并且直到将来某个不可知的时间才会执行该代码。

Then came AJAX, with its calls to the server. These calls could be configured to be synchronous, but developers generally preferred async calls and used callback methods to implement them.

然后是 AJAX,它调用服务器。这些调用可以配置为同步,但开发人员通常更喜欢异步调用并使用回调方法来实现它们。

Then, we saw the proliferation of JS libraries and toolkits. These strove to homogenize different browsers' implementations of things and built on the callback approach to async code. You also started to see a lot more synchronous callbacks for things like array iteration or CSS query result handling.

然后,我们看到了 JS 库和工具包的激增。这些努力使不同浏览器的事物实现同质化,并建立在异步代码的回调方法上。您还开始看到更多用于数组迭代或 CSS 查询结果处理之类的同步回调。

Now, we are seeing Deferreds and Promises in the mix. These are objects that represent the value of a long running operation and provide an API for handling that value when it arrives.

现在,我们看到了 Deferreds 和 Promises 的混合。这些对象表示长时间运行的操作的值,并提供 API 以在该值到达时对其进行处理。

NodeJS leans towards an async approach to many things; that much is true. However this is more a design decision on their part, rather than any inherent async nature of JS.

NodeJS 倾向于在很多事情上采用异步方法;这是真的。然而,这更多是他们的设计决定,而不是 JS 任何固有的异步性质。

回答by Deepak Sisodiya

Javascript is always a synchronous(blocking) single thread language but we can make Javascript act Asynchronous through programming.

Javascript 始终是一种同步(阻塞)单线程语言,但我们可以通过编程使 Javascript 成为异步的。

Synchronous code:

同步代码:

console.log('a');
console.log('b');

Asynchronous code:

异步代码:

console.log('a');
setTimeout(function() {
    console.log('b');
}, 1000);
setTimeout(function() {
    console.log('c');
}, 1000);
setTimeout(function() {
    console.log('d');
}, 1000);
console.log('e');

This outputs: a e b c d

这输出: aebcd

回答by Adam

In node long running processes use process.nextTick()to queue up the functions/callbacks. This is usually done in the API of node and unless your programming(outside the api) with something that is blocking or code that is long running then it doesn't really effect you much. The link below should explain it better then I can.

在节点中,长时间运行的进程用于process.nextTick()对函数/回调进行排队。这通常在 node 的 API 中完成,除非您的编程(在 api 之外)使用阻塞的东西或长时间运行的代码,否则它不会真正影响您。下面的链接应该比我能更好地解释它。

howtonode process.nextTick()

howtonode process.nextTick()

jQuery AJAX also takes callbacks and such as it its coded not to wait for server responses before moving on to the next block of code. It just rememebers the function to run when the server responds. This is based on XMLHTTPRequest object that the browsers expose. The XHR object will remember the function to call back when the response returns.

jQuery AJAX 也接受回调,例如它的编码在移动到下一个代码块之前不等待服务器响应。它只是记住服务器响应时运行的函数。这是基于浏览器公开的 XMLHTTPRequest 对象。当响应返回时,XHR 对象会记住要回调的函数。

setTimeout(fn, 0)of javascript will run a function once the call stack is empty (next available free tick) which can be used to create async like features.setTimeout(fn, 0) question on stackoverflow

setTimeout(fn, 0)一旦调用堆栈为空(下一个可用的免费滴答声),javascript 将运行一个函数,该函数可用于创建类似异步的功能。setTimeout(fn, 0) 关于 stackoverflow 的问题

To summerise the async abilities of javascript is as much to do with the environments they are programmed in as javascript itself. You do not gain any magic by just using lots of function calls and callbacks unless your using some API/script.

总结一下 javascript 的异步能力与编写它们的环境和 javascript 本身一样多。除非使用某些 API/脚本,否则仅使用大量函数调用和回调不会获得任何魔力。

Jquery Deferred ObjectIs another good link for async capabilities of jQuery. Googling might find you information on how jQuery Deferred works also for more insight.

Jquery Deferred Object是 jQuery 异步功能的另一个很好的链接。谷歌搜索可能会为您找到有关 jQuery Deferred 如何工作的信息,以获得更多见解。