了解 node.js 事件队列和 process.nextTick [英] understanding the node.js event queue and process.nextTick

查看:29
本文介绍了了解 node.js 事件队列和 process.nextTick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法准确理解 process.nextTick 是如何工作的.我以为我明白了,但我似乎无法复制我觉得这应该如何工作:

I'm having trouble understanding exactly how process.nextTick does its thing. I thought I understood, but I can't seem to replicate how I feel this should work:

var handler = function(req, res) {
    res.writeHead(200, {'Content-type' : 'text/html'});
    foo(function() {
        console.log("bar");
    });
    console.log("received");
    res.end("Hello, world!");
}

function foo(callback) {
    var i = 0;
    while(i<1000000000) i++;
    process.nextTick(callback);
}

require('http').createServer(handler).listen(3000);

foo 循环时,我将发送多个请求,假设 handler 将在 foo 后面与 多次排队>callback 仅在 foo 完成时入队.

While foo is looping, I'll send over several requests, assuming that handler will be queued several times behind foo with callback being enqueued only when foo is finished.

如果我对它的工作原理是正确的,我认为结果将如下所示:

If I'm correct about how this works, I assume the outcome will look like this:

received
received
received
received
bar
bar
bar
bar

但它不是,它只是连续的:

But it doesn't, it's just sequential:

received
bar
received
bar
received
bar
received
bar

我看到 foo 在执行 callback 之前正在返回,这是预期的,但似乎 callback 是 NEXT,而不是在队列的末尾,在所有进入的请求之后.这是它的工作方式吗?也许我只是不明白节点中的事件队列究竟是如何工作的.请不要在这里指向我.谢谢.

I see that foo is returning before executing callback which is expected, but it seems that callback is NEXT in line, rather than at the end of the queue, behind all of the requests coming in. Is that the way it works? Maybe I'm just not understanding how exactly the event queue in node works. And please don't point me here. Thanks.

推荐答案

process.nextTick 将回调放在将要执行的下一个滴答上,而不是滴答队列的末尾.

process.nextTick put the callback on the next tick that is going to be executed, not at the end of the tick queue.

Node.js 文档(http://nodejs.org/api/process.html#process_process_nexttick_callback) 说:它通常在任何其他 I/O 事件触发之前运行,但也有一些例外."

Node.js doc (http://nodejs.org/api/process.html#process_process_nexttick_callback) say: "It typically runs before any other I/O events fire, but there are some exceptions."

setTimeout(callback, 0) 可能更像你描述的那样工作.

setTimeout(callback, 0) will probably work more like you describe.

这篇关于了解 node.js 事件队列和 process.nextTick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆