I am using asynchronous functions in my JS application wrapped with my own functions that receive callback inputs. When i call the callback function, do I need to use the \"
If you only have one path through your function then you can use both forms pretty much interchangeably. Of course, the return value from the function will be undefined without the return, but your calling code is probably not using it anyway.
It's true that
return callback()
is practically equivalent to
callback(result); return;
The latter does result in an additional frame on the call stack, and so uses more resources. I suppose if you had many nested callbacks, or were doing recursion, you'd run out of stack space more quickly.
It's probably a bad idea and I don't think I'm sticking my neck out in saying that the return before the callback is way more idiomatic.
When you have multiple paths in your function, you have to be careful. For example, this will work as you expect:
(cb)=> {
if (something) cb('a')
else cb('b')
}
However, in this case, both callbacks will be called.
(cb)=> {
if (something) cb('a');
cb('b')
}
When you read the above, it's pretty clear that both will be called. Yet writing code like that is a classic node newbie mistake (especially when handling errors). If you want either or to be executed you need:
(cb)=> {
if (something) return cb('a');
cb('b')
}