Created
October 4, 2020 10:23
-
-
Save Kannndev/8d7930e3a390dee2d62d69cf44f29303 to your computer and use it in GitHub Desktop.
Medium - Promise.all Examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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