Skip to content

Instantly share code, notes, and snippets.

@AlexChesters
Created July 25, 2019 13:47
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 AlexChesters/54c7cf26248981d8d0907620cd5a4e58 to your computer and use it in GitHub Desktop.
Save AlexChesters/54c7cf26248981d8d0907620cd5a4e58 to your computer and use it in GitHub Desktop.
race promises
const invertPromise = (promise) => new Promise(
(resolve, reject) => promise.then(reject, resolve)
)
const raceToSuccess = (promises) => invertPromise(
Promise.all(promises.map(invertPromise))
)
const fast = () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve('fast')
}, 750)
})
}
const slow = () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve('slow')
}, 3000)
})
}
async function main () {
const promises = [fast(), slow()]
const first = await raceToSuccess(promises)
console.log('first was', first)
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment