r/javascript • • May 28 '19

What are some JavaScript things beginners don't know?

333 Upvotes

383 comments sorted by

View all comments

Show parent comments

12

u/pm_me_cute_rem_pics js/ux May 28 '19

Yeah especially waiting for promises to resolve and parallel stuff with async/await.

For example i see this in a lot of my code reviews with new js programmers:

// does some parallel async stuff
arrayOfItems.forEach(async item => {
    await doSomethingAsync(item)
})

doSomethingWhenDone()

This won't wait for the promise to actually resolve outside of the forEach and call doSomethingWhenDone(). If your program exist it will not wait for your async work to be done.

either do:

const pendingPromises = []

arrayOfItems.forEach(item => {
    pendingPromises.push(doSomethingAsync(item))
})

await Promise.all(pendingPromises)

doSomethingWhenDone()

Or if you like mapping over promises.

await Promise.all(
    arrayOfItems.map(async item => {
        await doSomethingAsync(item)
    })
)

doSomethingWhenDone()

examples https://repl.it/repls/WeeklyColorfulGraduate

1

u/[deleted] May 29 '19

How about Promise.each() ?

await Promise.each(arrayOfItems, function(item) {

return doSomethingAsync(item)

})

3

u/pm_me_cute_rem_pics js/ux May 29 '19

Promise.each is not vanilla js, but bluebird it looks like. So if you're not using bluebird you can't use Promise.each

1

u/tjb1019 May 29 '19

i like to use the for...of loop in this type of situation. seems like the cleanest syntax of all the options.

for (const item of arrayOfItems) {
   await doSomethingAsync(item);
}

doSomethingWhenDone();

2

u/justrhysism May 29 '19

I believe this would wait for each promise to resolve before moving onto the next loop.

The Promise.all() solution allows each async call to happen async concurrently; only moving on once all promises resolve (regardless of the order in which they resolve).

0

u/[deleted] May 29 '19

[deleted]

2

u/justrhysism May 29 '19

In that case doSomethingWhenDone() could execute before the promises inside the loop have resolved.

2

u/pm_me_cute_rem_pics js/ux May 29 '19

this will execute synchronously instead of parallel. If you want parallel this does not work unless you push the pending promise in an array.