Last active
December 6, 2021 02:57
-
-
Save hanksudo/0a15aad3a7b3ee3f8bd3bbe0a120437a to your computer and use it in GitHub Desktop.
nodejs promise race
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
let promiseA = new Promise((resolve) => { | |
const timeout = 100 + Math.floor(Math.random() * 1900) | |
setTimeout(() => resolve('A'), timeout); | |
console.log('A timeout', timeout) | |
}) | |
let promiseB = new Promise((resolve) => { | |
const timeout = 100 + Math.floor(Math.random() * 1900) | |
setTimeout(() => resolve('B'), timeout); | |
console.log('B timeout', timeout) | |
}) | |
let cancel = new Promise((_, reject) => { | |
const timeout = 100 + Math.floor(Math.random() * 1900) | |
setTimeout(() => { | |
reject("cancel") | |
}, timeout); | |
console.log('Cancel', timeout) | |
}) | |
async function start() { | |
await Promise.race([promiseA, promiseB, cancel]).then(results => { | |
console.log(results) | |
}).catch((error) => { | |
console.log(error) | |
}) | |
} | |
start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment