Navigate back to the homepage

How to Handle Concurrent Operations in Parallel in JavaScript?

Assume that you have more than one promise and you need to know when all the promises get resolved or you have to wait till all the promises resolve.

Ahmed Abdulrahman
Dec 27th, 2019 • ☕️ 1 min read
javascriptpromises6

Say when a user logs into a web app, you want to get back a bunch of data and several network requests probably need to be made to in order to get the data that you want?

Then we use Promise.all. It takes an array of Promises and turns them into a single Promise. Once all promises get resolved, we get data back. In case of any promises get rejected it’ll be required to exit Promise.all early.

1const product = [
2 new Promise(loadProduct),
3 new Promise(loadPrices),
4 new Promise(loadQuantity),
5];
6
7Promise.all(product) // 👈 get em all!
8 .then(response) // 📑 data
9 .catch(); // ❌ handle exception here

So, the main point of using Promise.all() is to take an array of Promises and turn them into a single Promise

Here we have another example, Notice the data in the response are ordered that is based on when the promise was “resolved.”

1const animals = [
2 new Promise((resolve, reject) => setTimeout(resolve, 200, '🦌')),
3 new Promise((resolve, reject) => setTimeout(resolve, 300, '🦒')),
4 new Promise((resolve, reject) => setTimeout(resolve, 100, '🐅')),
5 new Promise((resolve, reject) => setTimeout(resolve, 400, '🐘'))
6];
7
8Promise.all(animals)
9 .then(console.log)
10 .catch(console.log);

The result will be:

1["🐅", "🦌", "🦒", "🐘"]

If you would prefer using async/await and pure promises, this basic async/await syntax:

1let getFilms = async () => {
2 // Get Character Info.
3 let characterResponse = await fetch('http://swapi.co/api/people/1/')
4 // Resolve response
5 let characterResponseJson = await characterResponse.json()
6 /*
7 We have a list of films URLs, we can map over films URLs then wrap it
8 with Promise.all() to return a single Promise.
9 */
10 let films = await Promise.all(
11 characterResponseJson.films.map(async filmUrl => {
12 let filmResponse = await fetch(filmUrl)
13 return filmResponse.json()
14 })
15 )
16
17 return films
18}
19
20getFilms()

The result will be:

1[
2 { episode_id: 1, title: 'The Phantom Menace' },
3 { episode_id: 2, title: 'Attack of the Clones' },
4 { episode_id: 3, title: 'Revenge of the Sith' }
5]

To sum up, Promise.all() is really great when you have more than one promise in your code and you to make a concurrent operations by aggregating a list of promises to a single promise.

Did you find this useful? Buy me a coffee to give my brain a hug ☕️.

Hope you liked this article. If you did, then share it. It means a lot.🙌 Thanks for reading!


Discuss on TwitterFollow @_ahmed_ab

Other things I've written

ADD vs COPY in Docker

In this post, we'll learn what are ADD and COPY commands in docker, How they differ, and why COPY is more secure than ADD.

Mar 17th, 2020 · 1 min read

Understand the concept of Images and Containers

A step by step guide to understanding the concept of Images and Containers in Docker

Feb 13th, 2020 · 2 min read

© 2018–2020
Ahmed Abdulrahman

Contact
hello@aadev.me

Link to $https://twitter.com/_ahmed_abLink to $https://www.behance.net/ahmedabdulrahmanLink to $https://github.com/AhmedAbdulrahman