JavaScript回调函数在哪个线程执行?

4

最近我读了一些有关JavaScript的异步I/O内容,但是我对JavaScript在哪里执行其异步回调感到更加困惑。是在主线程还是其他地方?Node和浏览器有什么不同吗?


2
回调在主线程中执行,但异步操作则在其自己的线程中执行,具体取决于该操作。事件和计时器队列在主线程中更新,但 AJAX 调用有自己的线程。这也可能因实现而异。 - Teemu
1个回答

8

异步调用处理程序在响应返回时在主线程上执行。

如果您从WebWorker调用它,则异步调用处理程序将在WebWorker线程中处理。

它大致按照自上而下的方式设置。

parent thread
   |    
 async start 
   |
   - - - - - - > IO thread
   |                 |
 other stuff      make call
   |                 | 
 more stuff       get response
   |                 |
   | <--queue handling
   V
 handle async 
 response 

从技术上讲,nodejs处理io线程和浏览器的方式存在差异,但基本上你将获得相同的结果。

请看下面的示例,了解异步任务如何被推到另一个线程并继续执行主线程。随后,响应会被排队到主线程中,在处理程序完成时,主线程将继续其工作。

var request = new XMLHttpRequest();

request.open('GET', 'https://api.jikan.moe/meta/requests/anime/today');

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    console.log('Status:', this.status);
    console.log('Headers:', this.getAllResponseHeaders());
    console.log('Body:', this.responseText);
  }
};
var start = 0;
request.send();
for(var c=0;c<1000;c++) {
  +function(c) { 
     start += 1;
  
     window.setTimeout(function() {
       console.log(start, c);
     },c); 
   }(c)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hit f12 and scroll through the log output


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接