-
-
Save spion/4aad8c9c75ee4eaf60f6 to your computer and use it in GitHub Desktop.
Promise.any - async/await vs then()
This file contains hidden or 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 pending = new Promise((r,rj) => {}) | |
let waitForever = () => pending | |
let reject = Promise.reject.bind(promise) | |
let identity = x => x | |
let promiseTransform = fns => p => p.then(fns.fullfilment, fns.rejection) | |
function any(promises) { | |
let fulfillments = promises.map(promiseTransform({fullfilment: identity, rejection: waitForever})) | |
let rejections = promises.map(promiseTransform({fullfilment: waitForever, rejection: identity})) | |
let firstFulfill = Promise.race(fulfillments); | |
let allRejected = Promise.all(rejections) | |
return Promise.race([firstFulfill, allRejected.then(reject)]); | |
} |
This file contains hidden or 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
async function any(promises) { | |
let rejections = []; | |
for (let promise in promises) { | |
try { | |
return await promise; | |
} catch (reason) { | |
rejections.push(reason); | |
} | |
} | |
throw rejections; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment