I think this might actually answer another of my questions on Stack Overflow if I can get this confirmed.
What is the difference between returning a callback and just calling a callback?
I have seen code doing either/or/both and trying to wrap my head around why and when to do which.
function test(x, y, callback){
return callback(null, x);
callback(null, x + y);
}
test(1, 2, function(err, results){
if(!err){
console.log('results:\n', results);
} else {
console.error('err:\n', err);
}
});
Edit: I think part of my questions resolves around my linked question, where I would constantly get an error, callback already called.
I was trying to understand the conceptual difference between these two different ways to do in my mind the same thing. Not sure why I am getting voted down when I ask a question to better understand a concept I haven't grasped yet. Aren't we all here to expand on our knowledge of programming by asking questions of better programmers than ourselves?
return callback();
//some more lines of code;
the comment section won't be executed in above but will be in the below
callback();
//some more lines of code;
Edit :
Of course returning will help the context calling async function get the value returned by callback but usually async function are not called to assign anything.
Also, you use this trick usually with an if block, something like this :
asyncFunction (params, callback) {
if(err) callback(err, null);
callback(err, result);
}
To avoid callback being called twice you do something like this :
asyncFunction (params, callback) {
if(err) return callback(err, null);
callback(err, result);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With