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".
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.)
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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".Then you can use await and Array.prototype.reduce. It sounds a bit awkward but is actually straightforward.
I'm not sure I get your point (or whether you got mine), so I'll put some code:
Independent of using
map
orreduce
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 asurls.map(async (url) => await fetch(url))
and it's not different from usingreduce
to create that Array of Promises.But
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.)