1 import type { Cache } from '@proton/shared/lib/helpers/cache';
3 type CacheValue<V, D> =
14 * Cache a promise by a key, and re-run it when the dependency changes.
16 export const cachedPromise = <K, V, D>(
17 cache: Cache<K, CacheValue<V, D>>,
19 miss: () => Promise<V>,
22 const cachedValue = cache.get(key);
24 const { dependency: oldDependency } = cachedValue;
26 if (dependency === oldDependency) {
27 return 'promise' in cachedValue ? cachedValue.promise : Promise.resolve(cachedValue.result);
31 const promise = miss();
38 promise.then((result) => {
39 const cachedValue = cache.get(key);
42 throw new Error(`Cached value for ${key} was overwritten unexpectedly`);
45 if ('promise' in cachedValue && promise !== cachedValue.promise) {