Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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