【问题标题】:Is is bad practice to pass an empty callback in Javascript?在Javascript中传递空回调是不好的做法吗?
【发布时间】:2017-11-19 18:43:12
【问题描述】:

我有一个长时间运行的函数,我并不真正关心如何正确处理。将它与空回调一起交给事件循环并继续前进是不好的做法。像这样的:

var takeSomeTime = function(callback) {

  var count = 0,
      max = 1000,
      interval;

  interval = setInterval(function() {
    count++;
    if (count === max) {
      interval.clearInterval();
      return callback();
    }
  }, 1000);
};

var go = function(callback) {

  // do some stuff
  takeSomeTime(function(err) {
      if (err) {
          console.error(err)
      }
      // take all the time you need
      // I'm moving on to to do other things.
  });

  return callback();

};

go(function(){ 
  // all done... 
});

【问题讨论】:

  • 如果您不将函数传递给go(),那么return callback() 将失败并出现错误,指出callback is not a function
  • 哎呀。解决了这个问题。

标签: javascript memory-leaks callback event-loop


【解决方案1】:

我不知道您的问题与内存泄漏有什么关系,但通常可以想到传递空函数的有用应用。您基本上可以将一个空函数传递给第三方代码,它需要一个函数并且不检查它是否真的有一个。就像在您的示例或这个小型日志库中一样:

// Javascript enum pattern, snatched from TypeScript
var LogLevel;
(function (LogLevel) {
    LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
    LogLevel[LogLevel["WARN"] = 1] = "WARN";
    LogLevel[LogLevel["ERROR"] = 2] = "ERROR";
    LogLevel[LogLevel["FATAL"] = 3] = "FATAL";
})(LogLevel || (LogLevel = {}));
// end enum pattern

var noLog = function() {}; // The empty callback

function getLogger(level) {
    var result = {
        debug: noLog,
        warn: noLog,
        error: noLog
    };

    switch(level) {
        case LogLevel.DEBUG:
            result.debug = console.debug.bind(console);
        case LogLevel.WARN:
            result.warn = console.warn.bind(console);
        case LogLevel.ERROR:
            result.error = console.error.bind(console);
    }
    return result;
}

var log1 = LogFactory.getLogger(LogLevel.DEBUG);
var log2 = LogFactory.getLogger(LogLevel.ERROR);

log1.debug('debug test');// calls console.debug and actually displays the
    // the correct place in the code from where it was called.

log2.debug('debug test');// calls noLog
log2.error('error test');// calls console.error

您基本上将空函数 noLog 返回给我们库的使用者,以禁用特定日志级别的日志记录,但可以使用任意数量的参数调用它而不会引发错误。

【讨论】:

    猜你喜欢
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多