Last active
May 30, 2021 06:24
-
-
Save Arnavion/f1b709381669b98ab4ac to your computer and use it in GitHub Desktop.
Promise.first
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
async function first<T>(promises: Promise<T>[]): Promise<T> { | |
const rejections: any[] = []; | |
for (const promise of promises) { | |
try { | |
return await promise; | |
} | |
catch (reason) { | |
rejections.push(reason); | |
} | |
} | |
throw rejections; | |
} |
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
function first<T>(promises: Promise<T>[]): Promise<T> { | |
return first_rec(promises, []); | |
} | |
function first_rec<T>(promises: Promise<T>[], previousRejections: any[]): Promise<T> { | |
if (promises.length === 0) { | |
return Promise.reject(previousRejections); | |
} | |
const [head, ...tail] = promises; | |
return head.catch(reason => first_rec(tail, previousRejections.concat(reason))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment