nodejs using callback and event

I am new to nodejs programming. so be patient with me.

I have two nodejs modules. One passes passes a message to another nodejs module. the second processes it and pass result back to the first module.

method 1

first module

:
secondModule.callFunction(message, function(data){
    //deal with the return message from the second module

})
:

second module

:
function callfunction(message, callback){

   //asynchornous functions for processing
   callback(data);
} 
:

method 2

same thing but done using event emitters in the second module

first module

:
secondModule.callFunction(message){

})
secondModule.on('done_event', function(data){
    //deal with the reply
});
:

second module (uses event emitter)

 :

 function callFunction(message){

//asynchornous functions for processing
self.emit('done_event', data);
 } 
 :

Are they both correct. what is the difference in these things (both are asynchornous) or have i done something stupid.

Thanks in advance

Differences between plain callbacks and EventEmitter events (which is node's implementation of publisher-subscriber pattern)

  • You can attach multiple listeners to same event. Callbacks are one-to-one notifications, events - one-to-many.
  • You can't return value from event. Events are one way messages.
  • Often, callbacks follow (error, data1, data2, data3, ...) signature because single callback responsible for normal end error data flow (and async libraries usually expect this behaviour)
  • EventEmitter-based api, on the other hand tend to separate error and non-error messages
  • "error" event is special in event emitter: if there is no listener for it, EventEmitter throws an exception. With callbacks it's your responsibility to check first error parameter.

In your example both approaches are valid.

My understanding of events is that events are used when you want to "break" up your processing in pieces, and/or you don't really know when things are happening. So if your callFunction was a long running task (e.g. doing or waiting a lot for IO), you could break it into pieces and submitting, for instance, data events while it's processing, and then finish with a done event. However, if it's merely a "normal" function call, I would simply use a callback.