IIFE与函数调用(带参数),在循环内

时间:2016-11-21 19:11:05

标签: javascript function loops asynchronous iife

我在使用IIFE与使用for循环内的正常函数调用(带参数)之间感到困惑。

让我们说这个功能是 -

function print_doc_count(i){
    var str= "collection" + i.toString();
    db.collection(str).count(function(err, res){
        if(!err){
            console.log("docs in collection: "+str+" = "+res);
        }
    });
}


实施例1(无IIFE) -

for(var i=1; i<=10; i++){
    print_doc_count(i);
}

实施例2(使用IIFE) -

for(var i=1; i<=10; i++){
    (function print_doc_count(i){
        var str= "collection" + i.toString();
        db.collection(str).count(function(err, res){
            if(!err){
                console.log("docs in collection: "+str+" = "+res);
                // str needed closure, it contains the value i!
            }
        });
    })(i);
}


我的问题是上面的例子1和例子2有什么区别,应该优先于另一个(在什么情况下)?

1 个答案:

答案 0 :(得分:0)

正如@Kevin B在对该问题的评论中所述,示例1(没有IIFE)是一个更好的解决方案

from itertools import chain
from functools import reduce
from collections import Iterable  # or from collections.abc import Iterable
import operator
from iteration_utilities import deepflatten

def nested_list_comprehension(lsts):
    return [item for sublist in lsts for item in sublist]

def itertools_chain_from_iterable(lsts):
    return list(chain.from_iterable(lsts))

def pythons_sum(lsts):
    return sum(lsts, [])

def reduce_add(lsts):
    return reduce(lambda x, y: x + y, lsts)

def pylangs_flatten(lsts):
    return list(flatten(lsts))

def flatten(items):
    """Yield items from any nested iterable; see REF."""
    for x in items:
        if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
            yield from flatten(x)
        else:
            yield x

def reduce_concat(lsts):
    return reduce(operator.concat, lsts)

def iteration_utilities_deepflatten(lsts):
    return list(deepflatten(lsts, depth=1))


from simple_benchmark import benchmark

b = benchmark(
    [nested_list_comprehension, itertools_chain_from_iterable, pythons_sum, reduce_add,
     pylangs_flatten, reduce_concat, iteration_utilities_deepflatten],
    arguments={2**i: [[0]*5]*(2**i) for i in range(1, 13)},
    argument_name='number of inner lists'
)

b.plot()