Nexttick’s question

  node.js, question

I read in the book that node is a single thread. if the operation is carried out for a long time, it will block the process and affect the execution of other tasks. therefore, a recursive function can be converted into each step by using the process.nextTick method, which is assigned by the event cycle. I read it online and said the same thing. I excerpted some codes as follows

var http = require("http");
 
 var wait = function(mils) {
 var start = new Date().getTime();
 while(new Date().getTime() - start < mils);
 };
 
 function computer() {
 console.log("start computer");
 wait(1000);
 console.log("working for 1s, next tick");
 process.nextTick(computer);
 bracket
 
 http.createServer(function(req, res) {
 console.log("new request");
 res.writeHead(200, {'Content-Type': 'text/html'});
 res.end("Hello World");
 }).listen(5000, '127.0.0.1');
 
 computer();

However, after executing the js, the browser opened the web address and was always asking for it. It could not get a response from the server at all. Was node’s api changed or was it wrong to write this way?

According to my understanding,nextTickThe callback function was put before event queue. AndcreateServerAfter receiving the request, the callback function of will be placed at the end of the event queue. Therefore, the latter will never have a chance to implement it.

Maybe we should give it a trysetTimeout(compute, 0).

This is a passage from the official API document, which can exactly answer your question:

Note: the nextTick queue is completely drained on each pass of the event loop before additional I/O is processed. As a result, recursively setting nextTick callbacks will block any I/O from happening, just like a while(true); loop.

Links:process.nextTick(callback, arg)