2012-06-20 41 views
4

我一直在玩NodeJS最近,我發現自己被卡住了規律的問題:如何在JavaScript中處理條件回調,同時保持乾燥?

我已經運行在主運行,這取決於一些配置參數,我需要執行額外的步驟,但是這一步是異步:

if(request.config.save) { 

     fs.writeFile(request.config.save, decryptedData, function(err) { 
      // Continue the operation with a callback... 
      // Perform some other ops. 
      if(typeof callback == 'function') callback(decryptedData); 
     }.bind(this)); 

    } else { 

     // Continue the same operation without a callback 
     // Perform some other ops. 
     if(typeof callback == 'function') callback(decryptedData); 

正如你可以看到這個代碼是不會幹爲主體的結尾(回調)被調用兩次。

只有我看到的方式是使用功能(但再次函數調用未乾......和代碼可能是非常臃腫這樣...

那麼,有一個漂亮的忍者技巧來解決這個?

回答

3

那麼,一行代碼並不是那麼重複,但如果你做的不僅僅是它,它可能非常幹,那麼把你的最終邏輯包裝到一個函數中,然後調用在你的條件之內?

var endTick = function(){ 
    if(typeof callback == 'function') callback(decryptedData); 
} 

if(request.config.save) { 

    fs.writeFile(request.config.save, decryptedData, function(err) { 
     // Continue the operation with a callback... 
     // Perform some other ops. 
     endTick(); 
    }.bind(this)); 

} else { 

    // Continue the same operation without a callback 
    // Perform some other ops. 
    endTick(); 
} 
0
function cb() { 
    if (typeof arguments[0] === 'function') 
     arguments[0].apply(null, Array.prototype.slice.call(arguments,1)); 
} 

應不長於大約10個字符(可能需要bind),比普通的函數調用沒有typeof檢查,並假設沒有bind它不應該超過4

沒有無需付出某些代價即可解決此問題。

相關問題