Last active
October 13, 2021 02:11
-
-
Save qwtel/c597421f1dcc6f67a2c5230c13a1a8af to your computer and use it in GitHub Desktop.
Returns the first promise that resolves with a truthy value, or undefined if all promises resolve with a nullish value.
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
const NEVER = new Promise(() => {}); | |
async function raceTruthy(iterable) { | |
const ps = [...iterable].map(_ => Promise.resolve(_)); | |
let { length } = ps; | |
const continueWhenNullish = value => value != null | |
? value | |
: --length > 0 | |
? NEVER | |
: undefined; | |
return Promise.race(ps.map(p => p.then(continueWhenNullish))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Returns the first promise that resolves with a truthy value, or
undefined
if all promises resolve with a nullish value.Note that this inherits the behavior of
Promise.race
, where the returned promise rejects as soon as one input promise rejects.Example use case: Getting a cached response from a number of caches, without resorting to a lookup in all caches via
caches.match
: