Should I use ''return" with my callback function in Javascript?

前端 未结 3 1854
南笙
南笙 2020-12-10 21:25

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 \"

相关标签:
3条回答
  • 2020-12-10 21:48

    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')
    }
    
    0 讨论(0)
  • 2020-12-10 21:52

    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.

    0 讨论(0)
  • 2020-12-10 22:03

    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.

    0 讨论(0)
提交回复
热议问题