Search code examples
javascriptnode.jspromisebluebirdeventemitter

Node event emitter with condition


I've node app which raise event when I can run other logic, for example server.js will emit event when its up (just for example...),then I've logic which should be run after this event was raised

First File

server.js -> runProcess -> finish -> emit event

secondFile

listen to the event -> run new process

The problem is that firstFile/server.js is running just one time and secondFile can be multiple times so for the first time it works fine but for second the event is missing and the code will not be called...

Here it will be called for first time and I need it to be called for first time when the event available

But to the proxy.web which in second file can be called multiple times so in the second time it fails since the event is not raised anymore from the first file that not be called..., how can I overcome this ?

 Actions.eventEmitter.on('Available', function () {
            proxy.web(req, res, {
                target: 'http://' + hostname + ':' + appPort
            });

    })

Solution

  • You could use promises to solve that. In server.js you add this code.

    Actions.promiseAvailable = new Promise(function(resolve, reject) {
      Actions.eventEmitter.on('Available', function() {
        resolve();
      });
    });
    

    And in your second file you can then do this

    Actions.promiseAvailable.then(function() {
      //doSomething
    });
    

    The downside is you have to add another method for every type of event you could get.