DEV Community

Discussion on: Tell me an unpopular software opinion

Collapse
 
sesamestrong profile image
Sesamestrong

Depends what you're using then for. For performing operations on every element of an array or object, Array.prototype.map is really nice. But I definitely agree that for loops as opposed to Array.prototype.map, reduce and for each are never really bad; they're just sometimes not the best.

Collapse
 
karfau profile image
Christian Bewernitz

As soon as you need to have async code in your forEach callback you need to switch your code to the for loop again. So if there is any chance this might happen, pick it right away...

Thread Thread
 
diek profile image
diek

Nope, you can Promise.all()

Thread Thread
 
karfau profile image
Christian Bewernitz

How, .forEach doesn't collect the returned value, you would need to switch to .map and there are quite some cases where you don't want to fire all of these things "at once".

Thread Thread
 
sesamestrong profile image
Sesamestrong • Edited

Then you can use await and Array.prototype.reduce. It sounds a bit awkward but is actually straightforward.

Thread Thread
 
karfau profile image
Christian Bewernitz

I'm not sure I get your point (or whether you got mine), so I'll put some code:

Independent of using map or reduce to iterate over an array, the "aaync callback" will return the promise immediately for every item.
(Even the function that contains the await Promise.all will immediately return with a promise, of course)

The implication is that you can not run those async actions in a sequence using the methods provided by Array.protype.

Meaning urls.map(fetch) is the same as urls.map(async (url) => await fetch(url)) and it's not different from using reduce to create that Array of Promises.

But

for (const url of urls) {
  await fetch(url)
}

Will only trigger the second fetch after the first one is done.

I have had plenty of experience where servers have blocked to many simultaneous requests, so it's worth considering the impact the code can have.

(If that's not clear I'm willing to take the time to write a post about it.)

Collapse
 
jsbeaulieu profile image
Jean-Sébastien Beaulieu

I really don't like seeing people using .map for things not returning a new array. The whole concept of "mapping" comes from functional languages, or even higher, from mathematics, and always have been about "mapping" one set (your input) to another (the returned array). Discarding the output and using map as a glorified for loop makes the intention unclear.