DEV Community

Discussion on: Tell me an unpopular software opinion

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.)