node. JS Process.nexttick (callback) understands

Source: Internet
Author: User
Tags emit

node. js is single-threaded, based on the event loop, non-blocking IO . An event queue is used in an event loop, and at each point in time , the system processes only one event , even if the computer has multiple CPU cores and cannot handle multiple events concurrently. as a result,node. JS is suitable for applications that handle I/O types and are not suitable for CPU -intensive applications. In an I/O type application, a callback function is defined for each input and output , and node. js automatically joins it to the event polling processing queue, which is triggered when the I/O operation is complete. The system will continue to process other requests.

It is very easy to understand here, in the parable of the article on debuggable.com. As follows:

We wrote the JS code like a king, and Nodejs gave the king a lot of servants. In the morning, a servant woke the king and asked him what he needed. The king gave him a list of all the tasks that needed to be done, and then went back to sleep. When the king went back to sleep, the servant left the king, took the list, and assigned the other servants a task. The servants were busy each other until they had finished their task before they came back and gave the result to the king. The king summoned only one person at a time, and the others were waiting outside in line. After the king has disposed of the result, he may have given him a new assignment, or he would have just let him go, and then summoned the next person. When all the results were finished, the king went back to sleep. A new servant came to see him after he had finished the task. This is the king's happy life.

Process.nexttick (callback)

function: Calls the callback callback function in the next loop of the event loop. the effect is to defer a function until the next synchronization method written by the code finishes executing or when the event callback function of the Async method starts executing , similar to the function of the settimeout (FN, 0) function, but it is much more efficient.

Based on node. JS's event loop analysis, each cycle is tick, each tick, the V8 engine takes all events from the event queue and then processes them, and if it encounters a Nexttick event, joins it to the end of the event and waits for the next tick to execute; The result is that the Nexttick event Delayed execution; The following is the Nexttick source code

From these lines of code, we can see a lot of information:

    1. Nexttick really put a task at the end of the queue (Array.push)
    2. Nodejs in the execution of a task, the queue will be all the tasks are taken out, followed by execution
    3. If all goes well, delete all the tasks you just removed and wait for the next execution
    4. If there is an error in the middle, delete the completed task and the wrong task, waiting for the next execution
    5. If the first one goes wrong, the throw error

Here's a look at the scenario, which includes a compute-intensive operation that recursively handles without blocking the process:

  1. var http = require (' http ');
  2. var wait = function (mils) {
  3. var now = new Date;
  4. while (new Date -now <= mils);
  5. };
  6. function Compute () {
  7. //performs complicated calculations continuously
  8. Console.log (' Start computing ');
  9. Wait (1000);
  10. Console.log (' working for 1s, nexttick ');
  11. Process.nexttick (COMPUTE);
  12. }
  13. Http.createserver (function (req, res) {
  14. Console.log ('new request ');
  15. Res.writehead ($, {' Content-type ': ' Text/plain '});
  16. Res.end (' Hello world ');
  17. }). Listen (5000, ' 127.0.0.1 ');
  18. Compute ();

1, where compute is a dense calculation of the function, we make it recursive, each step requires 1 seconds (using wait instead of dense operation). Once executed, the next execution is placed at the end of the queue by Process.nexttick, and the client requests that are already waiting are processed instead. This allows both tasks to be taken into account, giving them both the opportunity to execute.

There are several ways to handle compute-intensive processing in node. JS:

    • Addon in C + + to implement, in the need for CPU-intensive computing, the JS code to the C + + code, for unfamiliar with C + + code, high cost
    • Use cluster to create multi-process processing, but the coding complexity is relatively high;
    • Modules that let node support multithreaded models: Threads_a_gogogithub Address: Https://github.com/xk/node-threads-a-gogo (more useful, refer to the introduction)

2, in addition: the relationship of the asynchronous model, leading to some code execution may precede the conditions they need to complete, so the need to put these pre-condition code into a callback function, and then put into the next event loop in the top level. Then the code will not be executed immediately, but wait until the next event is started and execute after startup.

Example:

var myconstructor=function(){ ...Process.Nexttick(function(){Self._continue();});}; Myconstructor.prototype.__proto__= Eventemitter.Prototype; Myconstructor.Prototype._continue=function(){Without the Process.nexttickThese events would be emitted immediatelyWith no listeners. They would be lost.This.Emit(' Data ',' Hello ');This.Emit(' Data ',' World ');This.Emit(' End ');};function (Req, Next  {var C = new Myconstructor (... on ( "data" function (Data{console.< Span class= "me1" >log (Data}) on ( ) ;}    

node. JS Process.nexttick (callback) understands

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.