Skip to content

Instantly share code, notes, and snippets.

@hanksudo
Last active December 6, 2021 02:57
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 hanksudo/0a15aad3a7b3ee3f8bd3bbe0a120437a to your computer and use it in GitHub Desktop.
Save hanksudo/0a15aad3a7b3ee3f8bd3bbe0a120437a to your computer and use it in GitHub Desktop.
nodejs promise race
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