Created
July 25, 2019 13:47
-
-
Save AlexChesters/54c7cf26248981d8d0907620cd5a4e58 to your computer and use it in GitHub Desktop.
race promises
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
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