Created
December 6, 2018 12:11
-
-
Save jbreckmckye/66364021ebaa0785e426deec0410a235 to your computer and use it in GitHub Desktop.
Get first truthy promise result
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
function firstTruthy<T>(promises: Array<Promise<any>>): Promise<T|null> { | |
return new Promise((resolve, reject) => { | |
// If any promise returns truthy value, immediately resolve with it | |
promises.forEach(async promise => { | |
const result = await promise; | |
if (!!result) resolve(result); | |
}); | |
// If any promise rejects, immediately throw the error | |
Promise.race(promises).catch(reject); | |
// If neither of the above fires, resolve with a null | |
// Check truthiness just in case callbacks fire out-of-band | |
Promise.all(promises).then(results => { | |
const truthyResult = results.find(result => !!result); | |
truthyResult ? resolve(truthyResult) : resolve(null); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment