简体   繁体   中英

how does reactor pattern work in Node.js?

在此处输入图像描述

I am reading Node.js Design Patterns. I am stuck in the understanding of the reactor pattern. I do not see any call stack here. I thought the call stack was one of the main parts of Node.js design. Can anyone please help me understand this diagram? Also, there is no callback queue.

Everything starts with the application, application makes requests and the event demultiplexer gathers those requests then forms queues, Event Queues. Event demultiplexer is run by libuv which is an asynchronous IO library that allows Node.js performs I/O.

In the diagram you see one event queue. actually there is not only 1 event queue, there are 7 basics queues. those queues have ascending priorities, the queue that highest priority checked first by the event loop.

Timers queue has the highest priority. setTimeout and setInterval functions get queued here. Once the events are done in this queue, or time is up, event loop passes those functions to call stack, in the diagram it is named execute handler.

Once one of the event queues are done, instead of jumping to next queue, event loop firstly will check 2 other queues which queues other micro tasks and process.nextTick functions. Then it will jump to next queue. this diagram will help u visualize the event loop. 在此处输入图像描述

If there are no events in the event queue or the Event Demultiplexer has no pending requests, the program will complete.

note:callback queue that mentioned is event queue and call stack is execute handler.

  1. The application generates a new I/O operation by submitting a request to the Event Demultiplexer.The application also specifies a handler, which will be invoked when the operation completes. Submitting a new request to the Event Demultiplexer is a non-blocking call and it immediately returns control to the application.
  2. When a set of I/O operations completes, the Event Demultiplexer pushes a set of corresponding events into the Event Queue.
  3. At this point, the Event Loop iterates over the items of the Event Queue.
  4. For each event, the associated handler is invoked.
  5. The handler, which is part of the application code, gives back control to the Event Loop when its execution completes (5a). While the handler executes, it can request new asynchronous operations (5b), causing new items to be added to the Event Demultiplexer (1).
  6. When all the items in the Event Queue are processed, the Event Loop blocks again on the Event Demultiplexer, which then triggers another cycle when a new event is available.

Credit to packtpub.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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