Skip to content

Instantly share code, notes, and snippets.

@Kannndev
Created October 4, 2020 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kannndev/8d7930e3a390dee2d62d69cf44f29303 to your computer and use it in GitHub Desktop.
Save Kannndev/8d7930e3a390dee2d62d69cf44f29303 to your computer and use it in GitHub Desktop.
Medium - Promise.all Examples
// Example 1:
const dog = new Promise((resolve, reject) => {
setTimeout(() => resolve('🐶'), 1000)
})
const cat = new Promise((resolve, reject) => {
setTimeout(() => resolve('🐈'), 2000)
})
Promise.all([dog, cat]).then((values) => {
// Order of values will be in the same order
// in which promises are present in the array
console.log(values) // ['🐶', '🐈']
})
// Example 2:
const bear = new Promise((resolve, reject) => {
setTimeout(() => reject('🐻'), 1000)
})
const panda = new Promise((resolve, reject) => {
setTimeout(() => resolve('🐼'), 2000)
})
Promise.all([bear, panda])
.then((values) => {
console.log(values)
})
.catch((error) => {
console.error(error) // 🐻
})
// Practical Usage:
// This would be useful in the case where
// you want to fetch data from multiple resources
// and then consolidate them to form a response
// before sending it back to the client.
Promise.all([
fetch('/endpoint0'),
fetch('/endpoint1'),
fetch('/endpoint2'),
]).then(response => console.log(response))
.catch(error => console.log(error))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment