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];67Promise.all(product) // π get em all!8 .then(response) // π data9 .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];78Promise.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 response5 let characterResponseJson = await characterResponse.json()6 /*7 We have a list of films URLs, we can map over films URLs then wrap it8 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 )1617 return films18}1920getFilms()
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!