map and promises javascriupt code example
Example 1: await inside map js
const mapLoop = async _ => {
console.log('Start')
const promises = fruitsToGet.map(async fruit => {
const numFruit = await getNumFruit(fruit)
return numFruit
})
const numFruits = await Promise.all(promises)
console.log(numFruits)
console.log('End')
}
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)))