|
8 | 8 |
|
9 | 9 | import { PromiseOrValue } from './type';
|
10 | 10 |
|
11 |
| -export type PromiseOrValueMap<K, V> = CacheLike<K, PromiseOrValue<V>>; |
| 11 | +export type PromiseOrValueMapLike<K, V> = { |
| 12 | + get(key: K): PromiseOrValue<V> | undefined; |
| 13 | + set(key: K, value: PromiseOrValue<V>): void; |
| 14 | +}; |
12 | 15 |
|
13 | 16 | export function getOrAdd<K, V>(
|
14 |
| - cache: PromiseOrValueMap<K, V>, |
| 17 | + cache: PromiseOrValueMapLike<K, V>, |
15 | 18 | key: K,
|
16 | 19 | compute: (key: K) => PromiseOrValue<V>,
|
17 | 20 | ): PromiseOrValue<V> {
|
18 | 21 | const existing = cache.get(key);
|
19 | 22 | if (existing) {
|
20 | 23 | return existing;
|
21 | 24 | }
|
22 |
| - const resultOrPromise = compute(key); |
23 |
| - cache.set(key, resultOrPromise); |
| 25 | + let resultOrPromise = compute(key); |
24 | 26 | if (resultOrPromise instanceof Promise) {
|
25 |
| - return resultOrPromise.then((result) => { |
| 27 | + // Return a promise that resolves after the cache has been updated |
| 28 | + resultOrPromise = resultOrPromise.then((result) => { |
26 | 29 | cache.set(key, result);
|
27 | 30 | return result;
|
28 | 31 | });
|
29 | 32 | }
|
| 33 | + cache.set(key, resultOrPromise); |
30 | 34 | return resultOrPromise;
|
31 | 35 | }
|
32 |
| - |
33 |
| -export type CacheLike<K, V> = { |
34 |
| - get(key: K): V | undefined; |
35 |
| - set(key: K, value: V): void; |
36 |
| -}; |
0 commit comments