promise all array map code example
Example 1: map with promise.all
let characterResponse = await fetch('http://swapi.co/api/people/2/')
let characterResponseJson = await characterResponse.json()
let films = await Promise.all(
characterResponseJson.films.map(async filmUrl => {
let filmResponse = await fetch(filmUrl)
return filmResponse.json()
})
)
console.log(films)
Example 2: promise.all map statement
const fetchGithubInfo = async (url) => {
console.log(`Fetching ${url}`)
const githubInfo = await axios(url)
return {
name: githubInfo.data.name,
bio: githubInfo.data.bio,
repos: githubInfo.data.public_repos
}
}
const fetchUserInfo = async (names) => {
const requests = names.map((name) => {
const url = `https://api.github.com/users/${name}`
return fetchGithubInfo(url)
.then((a) => {
return a
})
})
return Promise.all(requests)
}
fetchUserInfo(['sindresorhus', 'yyx990803', 'gaearon'])
.then(a => console.log(JSON.stringify(a)))