Should I use ''return" with my callback fu

2019-01-20 03:52发布

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.

3条回答
We Are One
2楼-- · 2019-01-20 04:21

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:

var getData = function(callback){
  dbStuff(function(err, results) {
    if (err) { callback(err, null); }
    callback(null, results);
  });
}

I generally consider it good practice to return when you are done...

var getData = function(callback){
  dbStuff(function(err, results) {
    if (err) { return callback(err, null); }
    return callback(null, results);
  });
}

But you can accomplish the same thing with if/else blocks and no return statements.

查看更多
Summer. ? 凉城
3楼-- · 2019-01-20 04:31

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 like callback(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.

查看更多
混吃等死
4楼-- · 2019-01-20 04:44

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

return callback()

is equivalent to

callback(result); return;

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:

(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')
}
查看更多
登录 后发表回答