In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "what is the concept of event cycle in Node.js". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the concept of event cycle in Node.js".
What is an event loop?
Although JavaScript is single-threaded, event loops use the system kernel as much as possible to allow Node.js to perform non-blocking Istroke O operations although most modern kernels are multithreaded, they can handle multithreaded tasks in the background. When a task is completed, the kernel tells Node.js, and then the appropriate callback will be added to the loop for execution. This article will cover this topic in more detail.
Time cycle interpretation
When Node.js starts execution, it first initializes the event loop and processes the input script provided (or put into REPL, which is not covered in this document), which executes an asynchronous API call, dispatches a timer, or calls process.nextTick (), and then begins to process the event loop
The following figure shows a simplified overview of the execution order of the event loop
┌──┐┌─ > │ timers ││ └─┬─┘│ ┌─┴─┐│ │ pending callbacks ││ └ ─┬─┘│ ┌─┴─┐│ │ idle Prepare ││ └─┬─┘ ┌─┐│ ┌─┴─┐ │ incoming: ││ │ poll │ {const delay = Date.now ()-timeoutScheduled Console.log (`${delay} ms have passed since I was organized`);}, 100); / / do someAsyncOperation which takes 95 ms to completesomeAsyncOperation (()) = > {const startCallback = Date.now (); / / do something that will take 10ms. While (Date.now ()-startCallback
< 10) { // do nothing }}); 当事件循环进入了 poll 阶段,是一个空的队列,(fs.readFile() 还没有完成),因此它会等待剩余的毫秒数直到最快的计时器阈值到达,当95 ms之后,fs.readFile() 完成了读文件并且会花费10 ms完成添加到poll 阶段并且执行完毕,当回调完成,队列中没有回调要执行了,事件循环循环返回到timers 阶段,执行计时器的回调。在这个例子中,你会看到计时器被延迟了105 ms之后执行 为了防止 poll 阶段阻塞事件循环,libuv(实现了事件循环和平台上所有的异步行为的C语言库)在 poll 阶段同样也有一个最大值停止轮训更多事件 pending callbacks 此阶段为某些系统操作(例如 TCP 错误类型)执行回调。 例如,如果 TCP 套接字在尝试连接时收到 ECONNREFUSED,则某些 *nix 系统希望等待报告错误。 这将在挂起的回调阶段排队执行。 poll poll 阶段有两个主要的功能 计算 I/O 阻塞的时间 执行 poll 队列中的事件 当事件循环进入到了poll阶段并且没有计时器,发生以下两种事情 如果 poll 队列中不为空,事件循环会同步地迭代执行每个回调直到执行所有,或者达到系统的的硬限制 如果 poll 队列是空的,以下两种情况会发生 如果是setImmediate的回调,事件循环会结束 poll 阶段并进入到 check 阶段执行回调 如果不是setImmediate,事件循环会等待回调添加到队列中,然后立即执行 一旦 poll 队列是空的,事件循环会检测计时器是否到时间,如果有,事件循环会到达timers 阶段执行计时器回调 check 此阶段允许人们在 poll 阶段完成后立即执行回调。 如果轮询阶段变得空闲并且脚本已使用 setImmediate() 排队,则事件循环可能会继续到 check 阶段而不是等待。 setImmediate() 实际上是一个特殊的计时器,它在事件循环的单独阶段运行。 它使用一个 libuv API 来安排在 poll 阶段完成后执行的回调。 通常,随着代码的执行,事件循环最终会到达 poll 阶段,它将等待传入的连接、请求等。但是,如果使用 setImmediate() 安排了回调并且 poll 阶段变得空闲,它将结束并继续 check 阶段,而不是等待 poll 事件。 close callbacks 如果一个 socket 或者操作突然被关闭(e.g socket.destroy()),close 事件会被发送到这个阶段,否则会通过process.nextTick()发送 setImmediate() VS setTimeout() setImmediate() 和 setTimeout() 是相似的,但是不同的行为取决于在什么时候被调用 setTimmediate() 在 poll 阶段一旦执行完就会执行 setTimeout() 在一小段时间过去之后被执行 每个回调执行的顺序依赖他们被调用的上下本环境,如果在同一个模块被同时调用,那么时间会受到进程性能的限制(这也会被运行在这台机器的其他应用所影响) 例如,如果我们不在I/O里边运行下面的脚本,尽管它受进程性能的影响,但是不能够确定这两个计时器的执行顺序: // timeout_vs_immediate.jssetTimeout(() =>{console.log ('timeout');}, 0); setImmediate (() = > {console.log (' immediate');}); $node timeout_vs_immediate.jstimeoutimmediate$ node timeout_vs_immediate.jsimmediatetimeout
However, if you move to the Imax O loop, the immediate callback will always be executed first.
/ / timeout_vs_immediate.jsconst fs = require ('fs'); fs.readFile (_ _ filename, () = > {setTimeout () = > {console.log (' timeout');}, 0); setImmediate (() = > {console.log ('immediate');});}); $node timeout_vs_immediate.jsimmediatetimeout$ node timeout_vs_immediate.jsimmediatetimeout
Process.nextTick ()
Although process.nextTick () is part of an asynchronous API, you may have noticed that it does not appear in the diagram because process.nextTick () is not part of the event loop technology. Instead, the nextTickQueue is executed after the current operation is executed, regardless of the current stage of the event loop. In this case, the operation is defined as a transformation from the underlying CumberCraft + handler and handles the JavaScript that needs to be performed. According to the diagram, you can call process.nextTick () at any stage, and all callbacks passed to process.nextTick () will be executed before the event loop continues, which can lead to some bad situations because it allows you to recursively call process.nextTick () "starve" your Igamo, which prevents the event loop from entering the poll phase.
Why is this allowed?
Why is this included in Node.js? Because Node.js 's design philosophy is that an API should always be asynchronous, even if it doesn't have to, take a look at the following snippet
Function apiCall (arg, callback) {if (typeof arg! = = 'string') return process.nextTick (callback, new TypeError (' argument should be string'));}
The fragment performs a parameter check and, if incorrect, passes the error to the callback. API has recently updated to allow arguments to be passed to process.nextTick (), which allows it to accept any arguments passed after the callback as arguments for the callback, so you don't have to nest functions.
By using process.nextTick (), we ensure that apiCall () always runs its callback after the rest of the user code and before allowing the event loop to continue. To achieve this, allow the JS call stack to expand and then immediately execute the provided callback, which allows people to make a recursive call to process.nextTick () without reaching RangeError: the maximum call stack size is exceeded from V8.
Thank you for your reading, the above is the content of "what is the concept of event cycle in Node.js". After the study of this article, I believe you have a deeper understanding of what the concept of event cycle in Node.js is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.