alf*_*alf 7 javascript callback eventqueue node.js
我很难理解它究竟是怎么process.nextTick回事.我以为我理解了,但我似乎无法复制我觉得这应该有效:
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);
Run Code Online (Sandbox Code Playgroud)
虽然foo是循环的,我会在几个请求发送,假设handler将排队几次身后foo有callback只在被排队foo完成.
如果我对这是如何工作正确的,我认为结果将如下所示:
received
received
received
received
bar
bar
bar
bar
Run Code Online (Sandbox Code Playgroud)
但它没有,它只是顺序的:
received
bar
received
bar
received
bar
received
bar
Run Code Online (Sandbox Code Playgroud)
我看到它foo在执行之前正在返回,callback这是预期的,但似乎callback是NEXT在队列中,而不是在队列的末尾,在所有请求进入后面.这是否有效?也许我只是不明白节点中的事件队列是如何工作的.请不要指我在这里.谢谢.
process.nextTick 将回调放在将要执行的下一个刻度上,而不是放在刻度队列的末尾。
Node.js 文档 ( http://nodejs.org/api/process.html#process_process_nexttick_callback ) 说:“它通常在任何其他 I/O 事件触发之前运行,但也有一些例外。”
setTimeout(callback, 0) 可能会更像你所描述的那样工作。
| 归档时间: |
|
| 查看次数: |
6710 次 |
| 最近记录: |