简体   繁体   中英

Node.js process.nextTick still blocking server from getting requests

I got this piece of code :

 import http from 'http'; function compute() { let [sum, i] = [1, 1]; while (i<1000000000) { 5*2 i++; } console.log("good"); process.nextTick(compute); } http.createServer((request, response) => { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello World'); }).listen(5000, '127.0.0.1'); http.request({hostname: '127.0.0.1', port: 5000}, (response) => { console.log("here !"); }).end(); compute(); 

the output for that is always : "good, "good" ... and the HTTP request didn't get called. I thought that process.nextTick should solve that problem, but server is still blocked. Why ? How can I fix it ?

Instead of process.nextTick rather use set setImmediate . Callbacks passed to nextTick are processed before IO callbacks whereas callbacks passed to setImmediate are processed after any that are already pending.

Replace process.nextTick(compute); with setImmediate(compute); .

Moving the CPU work to a child process or worker is also possible. But I won't describe that as my main point was to explain how:

function compute() {
  ...
  console.log("good");
  process.nextTick(compute);
}

would block the HTTP server from handling requests ignoring the while loop which has its own problem.

See setImmediate vs. nextTick for more.

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