Skip to content

Instantly share code, notes, and snippets.

@qwtel
Last active October 13, 2021 02:11
Show Gist options
  • Save qwtel/c597421f1dcc6f67a2c5230c13a1a8af to your computer and use it in GitHub Desktop.
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.
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)));
}
@qwtel
Copy link
Author

qwtel commented Oct 13, 2021

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:

const matching = await raceTruthy([
  caches.open(SHELL_CACHE).then(c => c.match(url)),
  caches.open(ASSETS_CACHE).then(c => c.match(url)),
  caches.open(CONTENT_CACHE).then(c => c.match(url)),
]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment