Skip to content

Instantly share code, notes, and snippets.

@rproenca
Last active June 27, 2019 14:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rproenca/08f88bc1478665507be149d41d1c3b11 to your computer and use it in GitHub Desktop.
Save rproenca/08f88bc1478665507be149d41d1c3b11 to your computer and use it in GitHub Desktop.
Javascript sequential vs parallel promise execution
const fetch = require('node-fetch')
async function fetchDogsImagesSequential(dogs) {
const images = []
for (const dog of dogs) {
const response = await fetch(`https://dog.ceo/api/breed/${dog}/images/random/3`)
const data = await response.json()
images.push({
[dog]: data.message
})
}
return images
}
async function fetchDogsImagesParallel(dogs) {
const promises = dogs.map(async function (dog) {
const response = await fetch(`https://dog.ceo/api/breed/${dog}/images/random/3`)
const data = await response.json()
return { [dog]: data.message }
})
return await Promise.all(promises)
}
(async () => {
const dogs = ["affenpinscher", "african", "airedale", "akita", "appenzeller", "basenji", "beagle", "bluetick", "borzoi", "bouvier", "boxer", "brabancon", "briard", "bulldog", "bullterrier", "cairn", "cattledog", "chihuahua", "chow", "clumber", "cockapoo", "collie", "coonhound", "corgi", "cotondetulear", "dachshund", "dalmatian", "dane", "deerhound", "dhole", "dingo", "doberman", "elkhound", "entlebucher", "eskimo", "frise", "germanshepherd", "greyhound", "groenendael", "hound", "husky", "keeshond"]
const hrstart1 = process.hrtime()
await fetchDogsImagesSequential(dogs)
const hrend1 = process.hrtime(hrstart1)
const hrstart2 = process.hrtime()
await fetchDogsImagesParallel(dogs)
const hrend2 = process.hrtime(hrstart2)
console.info('Sequential execution took: %ds %dms', hrend1[0], hrend1[1] / 1000000)
console.info('Parallel execution took: %ds %dms', hrend2[0], hrend2[1] / 1000000)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment