visit
This article is focusing on showing a brief explanation of how to use Promise.all in a real example that I used in one of my recent projects.
You can check the project in the following .
What is Promise.all
The scenario we are going to use and why Promise.all is useful in this example.
Check the for more information.
What do we want to achieve
We want to show a list of pokemon with the name of the pokemon with its respective image.Obstacles
returns a list of pokemon that contains the name but not the image URL, instead, it returns a URL where we can fetch more details of the pokemon including the image.How to solve this case using ES6
One way to solve this is using Promise.all, as we need to wait for all the promises to resolve (we are talking about fetching to the URL that we retrieved in the first fetch) to populate the list of pokemon with the name and the respective image.
How to combine Promise.all with fetch, map, async and await to make a cleaner code
const fetchPokemon = async () => {
const initial = await fetch('//pokeapi.co/api/v2/type/1')
const initialJson = await initial.json()
//console.log(initialJson.pokemon) // data array
const detailsData = initialJson.pokemon.map(async i => {
const preFetchData = await fetch(i.pokemon.url)
return preFetchData.json()
})
// uncomment this code if you want to see how it looks await Promise.all(detailsData)
// const response = await Promise.all(detailsData)
// console.log(response)
const payload = (await Promise.all(detailsData)).map(data => ({
name: data.name,
image: data.sprites['front_default']
}))
console.log(payload)
}
fetchPokemon()
Live Code
I hope this can help you, there is a ton of use cases where you can apply
Promise.all
, this is just one of them and, feel free to comment on this article if you like.Find me at Github and Twitter