【问题标题】:callback function within a loop raises a Lint error [duplicate]循环内的回调函数引发 Lint 错误 [重复]
【发布时间】:2014-01-11 22:45:40
【问题描述】:

我有一个循环用于向多个 HTTP 客户端发送一个 json 对象:

for(var i=0; i<clients.length; i++){
    request({
        method: 'POST',
        uri: clients[i].contact,
        json: obj
    },
    function(err, response, body){
        ....
    });     
}

Lint 告诉我“W083:不要在循环中创建函数”。 最干净的方法是什么? 最重要的是,我担心这种方法可能没有那么可扩展(尽管使用了 nodejs),对于大量客户端来说,合适的方法是什么?

【问题讨论】:

    标签: node.js jshint lint


    【解决方案1】:

    基准测试:在我的测试中,在循环外运行 20 倍

    // FILE: test.js
    
    // note: 1e9 == 10^9
    
    var begin, end;
    
    // TEST sum function outside 
    begin = process.hrtime();
    function sum(a, b) {
        return a + b
    }
    
    for(var i=0; i< 1e9; i++) {
        sum(i, i);
    }
    
    end = process.hrtime(begin);
    console.log('functions outside a loop = ', end[0] + end[1] / 1e9, 'seconds')
    
    // TEST sum function within a loop
    begin = process.hrtime();
    
    for(var i=0; i< 1e9; i++) {
        (function sum(a, b) {
            return a + b
        })(i, i);
    }
    
    end = process.hrtime(begin);
    
    console.log('functions within a loop = ', end[0] + end[1] / 1e9, 'seconds')
    

    结果:

    F:\damphat>node test.js
    functions outside a loop =  1.032908888 seconds
    functions within a loop =  20.298613718 seconds
    

    无论如何,我认为您不应该将回调移出循环,因为它不会提高您的案例的性能。只要保持你的代码干净和可读。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-14
      • 1970-01-01
      • 2018-12-27
      • 2016-07-23
      • 2020-08-15
      • 2021-05-28
      • 2016-09-28
      • 2022-10-14
      相关资源
      最近更新 更多