DEV Community

Discussion on: How to use async/await inside loops in JavaScript

Collapse
 
dylanwatsonsoftware profile image
Dylan Watson

I think in practice, I'd be horrified if someone tried to use a reduce over a simple for..of for such a simple case but it was a good article. Thanks!

Collapse
 
twelve profile image
nntwelve

Hello @dylanwatsonsoftware , I'm new with JS. I'm really curious about why you horrified, may you give me the best solution for this simple case? Thanks!!

Collapse
 
dylanwatsonsoftware profile image
Dylan Watson • Edited

Hmm just rereading the article. The example I was referring to is:

let result = [3000,2000,1000, 4000].reduce( (accumulatorPromise, nextID) => {
  return accumulatorPromise.then(() => {
    return testPromise(nextID);
  });
}, Promise.resolve());
Enter fullscreen mode Exit fullscreen mode

But you could write it much more simply, something like:

for(let nextID of [3000,2000,1000, 4000]) {
  await testPromise(nextID)
}
Enter fullscreen mode Exit fullscreen mode

Some cases you might need the first one... But usually the 2nd one is much easier to read, which means it's less likely to contain a bug.

Thread Thread
 
twelve profile image
nntwelve

Thank you, the 2nd is easy for me to understand, actually it took me a while to understand why the first one can run.