2014-09-21 41 views
0

獲取此警告在下面的代碼中創建函數:如何修復的JSLint警告不要循環

workflow.removeZSets = function(fn) { 
    var processed = 0; 
    for (var c = 1; c < 10; c++) { 
     workflow.removeZSet(c, function() { 
      processed++; 
      if (processed === 9) { 
       return fn(null, "finished removing"); 
      } 
     }); 
    } 
} 

workflow.removeZSet = function(precision, fn) { 
    rc.zrem("userloc:" + precision, function() { 

       return fn(null, 'done'); 
     }); 
    }); 
} 

有沒有人有一個建議,如何做到這一點,而不會觸發報警?

我有一些想法,像使用異步庫並行運行它們,但這是我在整個代碼庫中做的一件相當普遍的事情,所以對最佳方式的反饋非常感興趣。

+0

有什麼樣的警告?你能提供信息嗎? – magmel 2014-09-21 12:40:14

回答

1

錯誤是因爲您在for循環中定義了一個函數。

你可以嘗試這樣的事情,定義環外的函數:

workflow.removeZSets = function(fn) { 
    var processed = 0; 

    function removeZ(c) { 
    workflow.removeZSet(c, function(err) { 
     processed++; 
     if (processed === 9) { 
     return fn(null, "finished removing"); 
     } 
    }); 
    } 

    for (var c = 1; c < 10; c++) { 
    removeZ(c); 
    } 
} 

使用像異步庫做循環將有助於清理你的代碼,它可以讓你避免檢查,如果所有項目都已處理(處理=== 9),因爲它是由異步處理的。