在书上看到,由于node是单线程,如果长时间进行运算操作,就会阻塞进程,影响其他任务的执行,故可用process.nextTick方法将一个递归函数转换成各个步骤都由事件循环分派。网上看了下,也是如此说,摘录一些代码如下
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);
}
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();
但是执行这个js后,浏览器打开这个网址,始终在请求,根本得不到服务器的响应,是node的api改了吗还是这样写有错?
PHPz2017-04-17 13:19:03
According to my understanding, nextTick
places the callback function before the event queue. The callback function of createServer
will be placed at the end of the event queue after receiving the request. So, the latter never gets a chance to execute.
Maybe you should give it a trysetTimeout(compute, 0)
.
This is a passage from the official API document, which can 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.
Link: process.nextTick(callback, arg)