Search code examples
javascriptnode.jseventemitter

Event emitter not catching the event


My emitter.js file

const EventEmitter = require('events').EventEmitter;
var event = new EventEmitter();
export default event

I have another file in which I emit the event which I inside an api route

import Emitter from '../../config/emitter'

Emitter.emit('RIDING_STATUS', socketdriver)

And here I catch the event in index.js

import Emitter from '../config/emitter'

Emitter.on('RIDING_STATUS', async(data) => {
  console.log("Caught the event")
})

But problem is above event doesn't fire the RIDING_STATUS inside my index.js.

Can someone please let me know what I am doing wrong here.


Solution

  • You have a race condition. The order may not be well defined, however you are firing an event before the listener is attached.

    The following does not work (for example):

    const EventEmitter = require('events').EventEmitter;
    var event = new EventEmitter();
    
    event.emit('RIDING_STATUS');
    
    //will never be triggered as the emit has already been fired.
    event.on('RIDING_STATUS', async(data) => {
      console.log("Caught the event")
    });
    

    To make sure the event is emitted only after the listener is attached, put it in a setTimeout

    const EventEmitter = require('events').EventEmitter;
    var event = new EventEmitter();
    
    //Delay the emit event until after all setup code is complete
    setTimeout(()=>event.emit('RIDING_STATUS'),0);
    
    event.on('RIDING_STATUS', async(data) => {
      console.log("Caught the event")
    });
    

    The setTimeout ensures that all setup code is completed before the event emitter is fired.

    So, to quote your code above, the middle block of code should be:

    import Emitter from '../../config/emitter'
    
    setTimeout(()=>Emitter.emit('RIDING_STATUS', socketdriver),0)