简体   繁体   English

异步功能意味着没有阻塞,在javascript中呢?

[英]Asynchronous function means no blocking, what about in javascript?

Asynchronous function means no blocking, and mostly, it keeps with a callback function. 异步函数意味着没有阻塞,并且在大多数情况下,它与回调函数保持一致。 In c# and java, when calling function asynchronously, there must be more than one threads involved. 在c#和java中,异步调用函数时,必须涉及多个线程。 Thus, threads are doing job parallelly, and the callback function will be called when the asynchronous method is finished. 因此,线程正在并行执行工作,并且异步方法完成后将调用回调函数。

Language like javascript is single thread. 像javascript这样的语言是单线程的。 So how dose it implement the asynchronous function? 那么如何实现异步功能呢?

I read some articles and I know it take the event loop and setTimeout function to make a callback. 我读了一些文章,我知道它需要事件循环和setTimeout函数来进行回调。 But is it so-called asynchronous? 但这是异步的吗? Because I don't think it remove the blocking, because it is single thread. 因为我不认为它消除了阻塞,因为它是单线程。 (I know that ajax is real asynchronous,because it use another thread which is supported by browser) (我知道ajax是真正的异步的,因为它使用了浏览器支持的另一个线程)

Do I misunderstand something? 我会误会吗?

Javascript run synchronously (in one thread), but all I/O operations are asynchronous , that means that the calls are non-blocking, and when finished, the callback won't interrupt the running code, but will run synchronously once the current code is finished. Javascript 同步运行(在一个线程中),但是所有I / O操作都是异步的 ,这意味着调用是非阻塞的,并且在完成后,回调不会中断正在运行的代码,但是将在当前代码执行后同步运行完成。 So, it doesn't delay the blocking . 因此, 它不会延迟阻塞 Here is an example: 这是一个例子:

console.log("before async call");
setTimeout(function() { console.log("async stuff done"); }, 0);
console.log("after async call");

This will always display 这将始终显示

before async call
after async call
async stuff done

But now, if you do: 但是现在,如果您这样做:

console.log("before async call");
setTimeout(function() { console.log("async stuff done"); }, 0);
console.log("after async call");
while (true) {
  // Do nothing
}

This will just display: 这只会显示:

before async call
after async call

async stuff done is never displayed, because the while (true) lock the execution. 永远不会显示async stuff done ,因为while(true)会锁定执行。

@Joachim Isaksson: you and I both agree that asynchronous call is no blocking, but in javascript, asynchronous call using setTimeout function just delay the blocking, it never remove the blocking. @Joachim Isaksson:您和我都同意异步调用没有阻塞,但是在javascript中,使用setTimeout函数的异步调用只会延迟阻塞,它永远不会消除阻塞。

function f1(callback){
    setTimeout(function () {
      // f1's logic
      callback();
    }, 1000);
  }

  f1(f2);

As the codes, f1's logic will be delayed and when f1 is finished, it will callback the f2. 作为代码,f1的逻辑将被延迟,当f1完成时,它将回调f2。 It looks like asynchronous. 它看起来像异步的。 But it just delay the blocking. 但这只会延迟封锁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM