Created
October 4, 2020 10:26
-
-
Save Kannndev/f0c893b61181ce24cda6dc7209f0a9f3 to your computer and use it in GitHub Desktop.
Medium Promise.race 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.race([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(() => resolve('🐼'), 2000) | |
}) | |
Promise.race([bear, panda]) | |
.then((value) => { | |
console.log(value) | |
}) | |
.catch((error) => { | |
// value will be the rejected value of | |
// first promise which was rejected. | |
console.error(error) // 🐻 | |
}) | |
// Practical Usage: | |
// Here Promise will throw 'request timeout' | |
// if the api call takes more than 30 seconds | |
Promise.race([ | |
fetch('/endpoint'), | |
new Promise(function (resolve, reject) { | |
setTimeout(() => | |
reject(new Error('request timeout')), 30000) | |
}) | |
]).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