Node.js事件监听器被阻止了吗?

时间:2015-04-17 08:13:23

标签: javascript node.js events listener blocked

使用以下代码我注册一个node.js事件监听器,等待通过名为zmqevent的全局nodejs EventEmitter转发的zeromq连接的响应。

global.zmqevent.removeAllListeners(req.user._id)
global.zmqevent.on(req.user._id, function (msg, status) {
        console.log('event triggered');
});

global.zmq_controller_pub.send(recipient + " " + String(req.user._id) + " " + "getReportSingle");

console.log("1");
console.log("1");
console.log("1");
console.log("1");
console.log("1");
console.log("1");
console.log("1");
console.log("1");

基本上事件队列有效。 zmq_controller_pub.send向我的外部脚本发出请求,响应到达node.js,发出一个node.js事件,该事件触发上面定义的事件监听器。

如何让事件监听器在我的脚本末尾中断console.log()链? 当前输出如下:

1
1
1
1
1
1
1
1
event triggered

基本上我想等待来自我的zeromq连接的响应2秒并且如果没有响应到达则触发和替代“离线”结果。 但即使这个简单的例子也没有工作,事件只在我脚本的最后才被触发。 你有好主意吗?显然一定有一个愚蠢的错误......

2 个答案:

答案 0 :(得分:4)

你不能。

NodeJS(和io.js)中的JavaScript并发模型是所有同步代码在排除micro / macrotask队列上的任何事件处理程序之前运行。

这就是并发模型的工作方式,它实际上非常有用,因为永远不会出现使代码处于不一致状态的中断。

答案 1 :(得分:0)

如果我理解正确,你需要这样的东西:

var timeout    = null;
var didRespond = false;

// Wait for an event
global.zmqevent.removeAllListeners(req.user._id)
global.zmqevent.on(req.user._id, function (msg, status) {
  console.log('event triggered');

  // Remove the timeout so it won't trigger the handler anymore.
  clearTimeout(timeout);

  // If we already responded (due to the timeout), we don't respond here.
  if (didResponse) { 
    return;
  }

  // Send your response.
  ...
});

// I think the "removeAllListeners"/"on" combo can be folded into one "once":
// global.zmqevent.once(req.user._id, ...)

// Start a timer that triggers in two seconds.
timeout = setTimeout(function() {
  // Do the "offline" handling, since it took more than 2 seconds for the
  // event to arrive.
  didRespond = true;
  ...
}, 2000);