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)
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.