Last active
May 30, 2021 06:25
-
-
Save Arnavion/8496afcd4b6d40f20692 to your computer and use it in GitHub Desktop.
Promise.any - async/await vs then()
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 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; | |
} |
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 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)); | |
} |
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 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); | |
}); | |
}); | |
} |
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 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