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

前端 未结 3 1874
南笙
南笙 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 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.

提交回复
热议问题