我得到了这段代码:
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();
输出总是:“good,”good”... 并且未调用 HTTP 请求。 我认为 process.nextTick 应该可以解决这个问题,但服务器仍然被阻止。为什么 ?我该如何解决?
最佳答案
而不是 process.nextTick
而是使用 set setImmediate
。传递给 nextTick
的回调在 IO 回调之前处理,而传递给 setImmediate
的回调在任何已挂起的回调之后处理。
将 process.nextTick(compute);
替换为 setImmediate(compute);
。
将 CPU 工作转移到子进程或工作线程也是可能的。但我不会对此进行描述,因为我的主要观点是解释如何:
function compute() {
...
console.log("good");
process.nextTick(compute);
}
会阻止 HTTP 服务器处理忽略 while
循环的请求,这有其自身的问题。
参见 setImmediate vs. nextTick了解更多。
关于javascript - Node.js process.nextTick 仍然阻止服务器获取请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33330277/