Why should forEach be preferred over regular iterators?

后端 未结 6 643
北荒
北荒 2020-12-01 18:22

I was reading airbnb javascript guide. There is a particular statement, that says:

Don’t use iterators. Prefer JavaScript’s higher-order functions ins

6条回答
  •  囚心锁ツ
    2020-12-01 19:22

    forEach iterations cannot be delayed by await. This means you cannot use forEach to pipeline, let's say, web requests to a server.

    Also forEach is not present on async Iterables.

    Consider the following cases:

    1

    let delayed = (value)=>new Promise(resolve => setTimeout(() => resolve(value), 2000));
    
    
    (async ()=>{
        for(el of ['d','e','f'])console.log(await delayed(el))
        
    })();
    
    
    (async()=>{
        
        ['a','b','c'].forEach(async (el)=>console.log(await delayed(el)))
       
    })();
    

    Result:

    d
    a
    b
    c
    e
    f
    

    The elements of [d,e,f] array are printed every two seconds.

    The elements of [a,b,c] array are printed all together after two seconds.

    2

    let delayed = (value)=>new Promise(resolve => setTimeout(() => resolve(value), 2000));
    
    async function* toDelayedIterable(array) {
        for(a of array)yield (await delayed(a))    
    }
    
    
    for await(el of toDelayedIterable(['d','e','f']))console.log(el)
    
    toDelayedIterable(['a', 'b', 'c']).forEach(async(el)=>console.log(await el));
    
    

    Result:

    d
    e
    f
    Uncaught TypeError: toDelayedIterable(...).forEach is not a function
    

    The elements of [d,e,f] array are printed every two seconds.

    Error when trying to access forEach on the asyncIterator of [a,b,c] array.

提交回复
热议问题