Skip to content

Instantly share code, notes, and snippets.

@Arnavion
Last active May 30, 2021 06:25
Show Gist options
  • Save Arnavion/8496afcd4b6d40f20692 to your computer and use it in GitHub Desktop.
Save Arnavion/8496afcd4b6d40f20692 to your computer and use it in GitHub Desktop.
Promise.any - async/await vs then()
async function any<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 any<T>(promises: Promise<T>[]): Promise<T> {
return new Promise<T>((resolve, reject) =>
Promise.all<any>(promises.map(promise => promise.then(resolve, reason => reason))).then(reject));
}
function any<T>(promises: Promise<T>[]): Promise<T> {
const rejections: any[] = [];
return new Promise<T>((resolve, reject) => {
Promise.all<void>(promises.map((promise, index) =>
promise.then(resolve).catch(reason => {
rejections[index] = reason;
}))).then(() => {
reject(rejections);
});
});
}
function any<T>(promises: Promise<T>[]): Promise<T> {
let numLeft = promises.length;
const rejections: any[] = [];
return new Promise<T>((resolve, reject) => {
promises.forEach((promise, index) => {
promise.then(resolve).catch(reason => {
rejections[index] = reason;
}).then(() => {
numLeft--;
if (numLeft == 0) {
reject(rejections);
}
});
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment