Skip to content

Instantly share code, notes, and snippets.

@Kannndev
Created October 4, 2020 10:28
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/904401b9fbb2598170666efc972b1e17 to your computer and use it in GitHub Desktop.
Save Kannndev/904401b9fbb2598170666efc972b1e17 to your computer and use it in GitHub Desktop.
Medium Promise-any examples
// Example 1:
const dog = new Promise((resolve, reject) => {
setTimeout(() => reject('🐶'), 1000)
})
const cat = new Promise((resolve, reject) => {
setTimeout(() => resolve('🐈'), 2000)
})
Promise.any([dog, cat]).then((value) => {
// value will be the resolved value of
// first promise which resolved.
console.log(value) // '🐈'
})
// Example 2:
const bear = new Promise((resolve, reject) => {
setTimeout(() => reject('🐻'), 1000)
})
const panda = new Promise((resolve, reject) => {
setTimeout(() => reject('🐼'), 2000)
})
Promise.any([bear, panda])
.then((value) => {
console.log(value)
})
.catch((error) => {
// Array of rejected values
console.error(error) // ['🐻','🐼']
})
// Practical Usage:
// This can be used if we have multiple async calls
// and we are only interested in the first successful one.
Promise.any([
fetch('/endpoint'),
fetch('/alternateEndpoint'),
})
]).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