I was reading airbnb javascript guide. There is a particular statement, that says:
Don’t use iterators. Prefer JavaScript’s higher-order functions ins
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:
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.
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.