node.js - process.nextTick的疑问
天蓬老师
天蓬老师 2017-04-17 13:17:03
0
1
637

在书上看到,由于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改了吗还是这样写有错?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回覆(1)
PHPzhong

根據我的理解,nextTick是將回呼函數放到事件佇列之前的。而createServer的回呼函數在收到請求後會被放到事件佇列結尾。所以,後者永遠沒有機會執行。

也許應該試試看setTimeout(compute, 0)

這是官方API文件中的一段話,剛好可以解答你的問題:

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 / j (true); loop.

連結:process.nextTick(callback, arg)

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板