2017-06-16 49 views
-2

我有一個長時間運行的功能,我並不真正關心正確處理。將它交給事件循環以及空回調並繼續前進,這是不好的做法嗎?事情是這樣的:在JavaScript中傳遞空回調是不好的做法嗎?

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... 
}); 
+0

如果你沒有把函數傳給'go()',那麼'return callback()'將會失敗,並顯示錯誤,說明'回調函數不是函數'0ops –

+0

oops。固定的。 – Pardoner

回答

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回到我們圖書館的消費者,以禁用日誌記錄特定日誌級別,但它可以被稱爲任何數量的參數都不會引起錯誤。

相關問題