Wednesday, October 31, 2018

node.js - NodeJS callback and return statement

I'm writing a Server-side application based on NodeJS.
The application listen on some TCP and UDP ports for incoming messages, when the messages arrive they are parsed and the relevant data are stored into a MySQL database. The whole thing works fine and NodeJS capability to handle parallel concurrent requests is amazing.
However reading around the feedback about NodeJS dangers I've found something that brings confusion to me: the question is about callbacks.
Imagine the code below:



function ParseMessage(payload,callback_ko,callback_ok) {
// here we evaluate the parsed_message content, err is set if parsing errors occurs
....
if(!err) {
// if there are no errors invoke the callback_ok to let the flow continue passing the parsed content
if(typeof callback_ok == 'function') {
callback_ok(parsed_message);
}
else {
// if error occurs invoke the callback_ko passing the payload to let the flow continue in another path, maybe attempt another parsing
if(typeof callback_ko =='function') {
callback_ko(payload);
}
}
return; // <---- Ensure the functions ends
}


The code if(typeof callback == 'function') is placed to avoid to call arguments passed to ParseMessage function that is not a function (in that case the ParseMessage simply must exit returning anything as result).
My doubt is about the return; statement:
I know the return statement MUST always be present (correct me if I'm wrong with that) in order to allow the async function ends properly. As we're not returning anything here (we're invoking callbacks here) we simply don't return anything on it, but I don't know if the place where return statement is written is the right one. In other words, should I place the return statement at the end of the function or should I have something like this, instead:



function ParseMessage(payload,callback_ko,callback_ok) {
// here we evaluate the parsed_message content, err is set if parsing errors occurs
....
if(!err) {
// if there are no errors invoke the callback_ok to let the flow continue passing the parsed content
if(typeof callback_ok == 'function') {
callback_ok(parsed_message);
}
return; // <---- Ensure the functions ends
else {
// if error occurs invoke the callback_ko passing the payload to let the flow continue in another path, maybe attempt another parsing
if(typeof callback_ko =='function') {
callback_ko(payload);
}
return; // <---- Ensure the functions ends
}
}


I've found that someone also suggest to write something like return callback(payload);. What's the most correct strategy?

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...