Node.js的process.nextTick仍然阻止服务器获取请求

我得到这段代码:

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(); 

输出的总是:“好,”好“…和HTTP请求没有被调用。我认为process.nextTick应该解决这个问题,但服务器仍然被阻止。为什么?我该如何解决它?

而不是process.nextTick而是使用set setImmediate 。 传递给nextTick的callback会在IOcallback之前处理,而传递给setImmediatecallback会在任何已经挂起的处理之后进行处理。

replaceprocess.nextTick(compute);setImmediate(compute);

将CPU工作转移到subprocess或工作者也是可能的。 但我不会形容这一点,因为我的主要观点是解释:

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

会阻止HTTP服务器处理请求,忽略具有自己问题的while循环。

有关更多信息,请参阅setImmediate与nextTick 。