0

Is it bad practice to emit events with callbacks as arguments in node?

var someonesListened = self.emit('doSomething', param, callback);

if (!someonesListened) {
  callback();
}


// in another module somewhere
this.on('doSomething', function(param, callback) {
    // Something async....

    // Then sometime later 
    callback();
})

EDIT: After writing this question I realised that by providing a continuation callback to an event that can be intercepted by multiple listeners defeats the purpose so I don't think I will be taking this approach.

Tim Fairbrother
  • 928
  • 2
  • 9
  • 20

2 Answers2

0

No, it's not a bad practice if you know what are you doing.

But keep in mind that this callback could be called multiple times, or not called at all depending on how many listeners there are. If you're fine with that, by all means use callbacks.

alex
  • 11,935
  • 3
  • 30
  • 42
0

I'm having to try and read between the lines, but it appears that you have the following requirements:

  • You have a callback that needs to run exactly once.
  • If no one else invokes the callback, you need to do it yourself, but...
  • ...someone else may invoke that callback asynchronously.

Assuming that this is the case, you could use an approach like this:

// define a callback that will exit early if it has already been invoked,
// AND will invoke itself after a 10 second delay, if no one else has.
var hasRun = false, timeoutId = setTimeout(callback, 10000);
function callback() {
    if (hasRun) return;

    hasRun = true;
    clearTimeout(timeoutId);

    // do something cool
}

self.emit('some-event', callback);

But, of course, I may have completely misread your requirements :)

jmar777
  • 38,796
  • 11
  • 66
  • 64
  • I was using an event to try an decouple the modules. For example, if someone is listening, then doSomething and tell me when your done. If no one is listening, just carry on. As I noted in my edit, it is a bit misleading when you can broadcast an event that multiple consumers can listen on but only one of them can fire the next callback. I know I could engineer something that fits this requirement but I've ditched this approach now. – Tim Fairbrother Apr 02 '14 at 03:03