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 "return" keyword? does it matter? whats the difference?
eg:
var getData = function(callback){
// do some aysnc db stuff...
return callback(results);
// or just
callback(results);
}
PS: I am writing a hybrid mobile appiliction using javascript.
You don't have to, but you might run into trouble if you don't use 'return'. For example, error handling can become problematic if you're not used to making early returns. As an example:
I generally consider it good practice to return when you are done...
But you can accomplish the same thing with if/else blocks and no return statements.
No, callback should not be used with return.
I'd never expect a callback-function to return a value. The callback replaces the return in terms of passing a value when the (async) computation is done.
You can use this Syntax
return callback(result)
as a shortcut for likecallback(result); return;
but it may confuse some further Team-member, what kind of value callback might return.This is actually a task for your minifyer, to create such code; not yours.
If you only have one path through you 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
is equivalent to
but I'll stick my neck out and say that the former is more idiomatic.
When you have multiple paths in your function, you have to be careful. For example, this will work as you expect:
However, in this case, both callbacks will be called.
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: