繁体   English   中英

Node.js事件侦听器被阻止?

[英]Node.js event 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秒钟,如果没有响应到达,则触发并触发“离线”结果。 但是,即使这个简单的示例也无法正常工作,并且仅在脚本的最后才触发该事件。 你有想法吗? 显然必须有一个愚蠢的错误。

你不能

NodeJS(和io.js)中JavaScript的并发模型是, 所有同步代码都将在耗尽微/宏任务队列上安排的任何事件处理程序之前运行。

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

如果我理解正确,则您需要以下内容:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM