Skip to content

Instantly share code, notes, and snippets.

@hanksudo
Last active Dec 6, 2021
Embed
What would you like to do?
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