찾다

 >  Q&A  >  본문

node.js - process.nextTick的疑问

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

天蓬老师天蓬老师2784일 전614

모든 응답(1)나는 대답할 것이다

  • PHPz

    PHPz2017-04-17 13:19:03

    根据我的理解,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 any I/O from happening, just like a while(true); loop.

    链接:process.nextTick(callback, arg)

    회신하다
    0
  • 취소회신하다