最近我读了一些有关JavaScript的异步I/O内容,但是我对JavaScript在哪里执行其异步回调感到更加困惑。是在主线程还是其他地方?Node和浏览器有什么不同吗?
最近我读了一些有关JavaScript的异步I/O内容,但是我对JavaScript在哪里执行其异步回调感到更加困惑。是在主线程还是其他地方?Node和浏览器有什么不同吗?
异步调用处理程序在响应返回时在主线程上执行。
如果您从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