0

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
            });

    })
  • Events are fired only once and will trigger callbacks only when they are fired. You could try using a promise instead. They trigger callbacks even after they were completed. Just register an event handler that completes the promise and add all your callbacks to that promise. – Tesseract Jan 17 '16 at 15:52
  • @SpiderPig - I use bluebird but not sure how to use promise here and how can it helps, can you please provide example ? –  Jan 17 '16 at 15:54
  • Events are ephemeral, not stateful. You need some sort of semaphore system. In response to an event something needs to permanently change state, and remain in scope of later event handers. Promises are indeed stateful in the right way (once settled they stay settled) but would be overkill. All you need is the "callback queue" aspect of Promises - the observer pattern that allows success/error callbacks to be added and fired at some point. jQuery exposes this aspect in the form of [jQuery.Callbacks](https://api.jquery.com/jQuery.Callbacks/). I'm sure the code could be cribbed from the source. – Roamer-1888 Jan 17 '16 at 23:52

1 Answers1

0

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.

Tesseract
  • 8,049
  • 2
  • 20
  • 37
  • Thanks but the server.js file (first) need to **emit** the event and not to listen(on) to it... –  Jan 17 '16 at 16:03