在书上看到,由于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改了吗还是这样写有错?
根據我的理解,
nextTick
是將回呼函數放到事件佇列之前的。而createServer
的回呼函數在收到請求後會被放到事件佇列結尾。所以,後者永遠沒有機會執行。也許應該試試看
setTimeout(compute, 0)
。這是官方API文件中的一段話,剛好可以解答你的問題:
連結:process.nextTick(callback, arg)