Skip to content

Instantly share code, notes, and snippets.

@jbreckmckye
Created December 6, 2018 12:11
Show Gist options
  • Save jbreckmckye/66364021ebaa0785e426deec0410a235 to your computer and use it in GitHub Desktop.
Save jbreckmckye/66364021ebaa0785e426deec0410a235 to your computer and use it in GitHub Desktop.
Get first truthy promise result
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