JavaScript 如何在后台处理 AJAX 响应?
由于 JavaScript 在单线程中运行,在发出 AJAX 请求后,后台实际发生了什么?我想对此有更深入的了解,有人能解释一下吗?
Since JavaScript runs in a single thread, after an AJAX request is made, what actually happens in the background? I would like to get a deeper insight into this, can anyone shed some light?
推荐答案
在底层,javascript 有一个事件队列.每次 javascript 线程执行完成时,它都会检查队列中是否有另一个事件要处理.如果有,它会将其从队列中拉出并触发该事件(例如鼠标单击).
Below the covers, javascript has an event queue. Each time a javascript thread of execution finishes, it checks to see if there is another event in the queue to process. If there is, it pulls it off the queue and triggers that event (like a mouse click, for example).
位于 ajax 调用下的本机代码网络将知道 ajax 响应何时完成,并且事件将被添加到 javascript 事件队列中.本机代码如何知道 ajax 调用何时完成取决于实现.它可以用线程实现,也可以由事件驱动本身(这并不重要).实现的重点是,当ajax响应完成后,一些native代码会知道它已经完成,并将一个事件放入JS队列中.
The native code networking that lies under the ajax call will know when the ajax response is done and an event will get added to the javascript event queue. How the native code knows when the ajax call is done depends upon the implementation. It may be implemented with threads or it may also be event driven itself (it doesn't really matter). The point of the implementation is that when the ajax response is done, some native code will know it's done and put an event into the JS queue.
如果当时没有 Javascript 正在运行,则将立即触发该事件,该事件将运行 ajax 响应处理程序.如果当时正在运行某些东西,那么当当前执行的 javascript 线程完成时,将处理该事件.javascript引擎不需要进行任何轮询.当一段 Javascript 完成执行时,JS 引擎只是检查事件队列以查看是否还有其他需要运行的内容.如果是这样,它会从队列中弹出下一个事件并执行它(调用为该事件注册的一个或多个回调函数).如果事件队列中没有任何内容,则 JS 解释器有空闲时间(垃圾收集或空闲),直到某个外部代理将其他内容放入事件队列并再次唤醒它.
If no Javascript is running at the time, the event will be immediately triggered which will run the ajax response handler. If something is running at the time, then the event will get processed when the current javascript thread of execution finishes. There doesn't need to be any polling by the javascript engine. When a piece of Javascript finishes executing, the JS engine just checks the event queue to see if there is anything else that needs to run. If so, it pops the next event off the queue and executes it (calling one or more callback functions that are registered for that event). If nothing is in the event queue, then the JS interpreter has free time (garbage collection or idle) until some external agent puts something else in the event queue and wakes it up again.
因为所有外部事件都经过事件队列,并且在 javascript 实际运行其他东西时不会触发任何事件,所以它保持单线程.
Because all outside events go through the event queue and no event is ever triggered while javascript is actually running something else, it stays single threaded.
这里有一些关于细节的文章:
Here are some articles on the details:
- Javascript 定时器如何工作 - 由 John Resig 编写
- 事件和时序深度
- W3 规范:HTML5 事件循环
- 关于事件循环的 MDN 文章
- JS 事件队列演示
- JavaScript 事件循环:解释
- 帮助驯服异步 Javascript 的五种模式
- Javascript 事件循环演示
- 视频讨论 Javascript 的工作原理(包括 10:27 的事件循环)李>
相关文章