Let’s say we have a list of names. For each name, we want to make an API call and get some information, and then keep a new list with this collection of information. A typical approach may look like this.
Refactoring to using map
or forEach
is not that straightforward here. The callbacks provided to map
or forEach
(or any of the array-methods) are not awaited, so we have no way of knowing when the full collection of information is done and ready to use. However, there is still a way we can write this in a nice way. Using the Promise.all
method.
Awesome! Now, map
returns a list of promises, and the Promise.all
method takes a list of promises and resolves them in parallel. Not only did the code become much more nice and clean - but we also beneļ¬t from the fact that the promises are not resolved sequentially, which speeds up the process and increases performance.