Home Ask Login Register

Developers Planet

Your answer is one click away!

Nicolas Durán February 2016

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.

Answers


cybersam February 2016

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


Nicolas Durán February 2016

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.

Post Status

Asked in February 2016
Viewed 2,171 times
Voted 10
Answered 2 times

Search




Leave an answer


Quote of the day: live life