Skip to content

Instantly share code, notes, and snippets.

@Arnavion
Last active May 30, 2021 06:24
Show Gist options
  • Save Arnavion/f1b709381669b98ab4ac to your computer and use it in GitHub Desktop.
Save Arnavion/f1b709381669b98ab4ac to your computer and use it in GitHub Desktop.
Promise.first
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;
}
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