JavaScript Async Ready Looping
When you are following functional programming style guide to write JavaScript, you may find that it’s hard to deal with asynchronous since async
function always return promises. So code like below will resolve the promises at same time instead of waiting for them.
1 | (() => { |
There are several different approaches to solve this problem.
Promise.all
You can simply take advantage of Promise.all()
to create a promise out of an array of promises.
1 | (() => { |
Use Reduce
to loop over async calls [promise chain]
Since async
calls return promises, we can emulate forEach
with reduce
by starting with a resolved promise and chaining ot it the promise for each value in the array.
1 | (async () => { |