简体   繁体   中英

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][, ...])

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:

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.

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.

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. 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() .

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.

Sorry about that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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