[英]Is there a way to emit end event to all listeners at the same time with Node.js EventEmitter?
As the docs says, emitter.emit(event[, arg1][, arg2][, ...])
就像文档所说的,
emitter.emit(event[, arg1][, arg2][, ...])
Synchronously calls each of the listeners registered for event, in the order they were registered, passing the supplied arguments to each.
按照注册事件的顺序,同步调用为事件注册的每个侦听器 ,并将提供的参数传递给每个侦听器 。
But with this simple example: 但是用这个简单的例子:
router.get('/messages', function(req, res, next) {
var addMessageListener = function(res){
messageBus.once('message', function(data){
res.json(data);
})
}
addMessageListener(res);
});
router.get('/push', function(req, res, next) {
messageBus.emit('message', { awesome : 'event'})
res.status(200).end()
});
When message event is emitted and two request are listening, only one of them listen properly to the event and execute its callback. 当发出消息事件并且正在侦听两个请求时,只有其中一个可以正确侦听该事件并执行其回调。
Is there a way to emit the event to all listeners at the same time? 是否可以将事件同时发送给所有侦听器?
edit: 编辑:
I didnt need the listeners to execute at the exact same time, I just need to execute all of them 我不需要监听器在同一时间执行,我只需要执行所有监听器
edit 2: 编辑2:
After more testing, when I create more than one listener, they are successfully listening to the emitter (debugged with messageBus.listenerCount('message')
) but with an almost 20 seconds delay. 经过更多测试后,当我创建多个监听器时,它们成功地监听了发射器(已使用
messageBus.listenerCount('message')
调试),但延迟了将近20秒。
And when only one is listening and the second one is during this delay, if I call /push
it successfully emit to the listening one and the other one immediately start listening. 当只有一个正在监听并且第二个在此延迟期间时,如果我调用
/push
它将成功发送给正在监听的一个,而另一个立即开始监听。
Since you used the once() function to add the listener, node will call the specified listener at most once , and after the first call it will remove that listener. 由于您使用了after ()函数添加侦听器,因此节点最多将调用一次指定的侦听器,并且在第一次调用之后,它将删除该侦听器。 If you are expecting the listener to be called every time a
message
event is emitted, you need to use the on() function instead of once()
. 如果您希望每次发出
message
事件时都调用该侦听器,则需要使用on()函数而不是once()
。
Ok reading this comment I found that when testing, Chrome will not request the same url again after the first one was responded or after the mentioned delay. 好的阅读此评论后,我发现在测试时,Chrome在第一个响应或提及的延迟之后将不再再次请求相同的URL。
Sorry about that. 对于那个很抱歉。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.