Skip to content

Commit 2df3d63

Browse files
committed
bug fix
1 parent 1e0ef0a commit 2df3d63

File tree

2 files changed

+15
-10
lines changed

2 files changed

+15
-10
lines changed

Diff for: src/cache.test.ts

+6
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,13 @@ describe('getOrAdd', () => {
1515
const fn = jest.fn(() => Promise.resolve(5));
1616
await expect(getOrAdd(cache, 'foo', fn)).resolves.toBe(5);
1717
expect(getOrAdd(cache, 'foo', fn)).toBe(5);
18+
expect(fn).toHaveBeenCalledTimes(1);
19+
20+
const bar = getOrAdd(cache, 'bar', fn);
21+
expect(bar).toBeInstanceOf(Promise);
22+
expect(getOrAdd(cache, 'bar', fn)).toBe(bar);
1823
await expect(getOrAdd(cache, 'bar', fn)).resolves.toBe(5);
24+
expect(getOrAdd(cache, 'bar', fn)).toBe(5);
1925
expect(fn).toHaveBeenCalledTimes(2);
2026
});
2127
});

Diff for: src/cache.ts

+9-10
Original file line numberDiff line numberDiff line change
@@ -8,29 +8,28 @@
88

99
import { PromiseOrValue } from './type';
1010

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+
};
1215

1316
export function getOrAdd<K, V>(
14-
cache: PromiseOrValueMap<K, V>,
17+
cache: PromiseOrValueMapLike<K, V>,
1518
key: K,
1619
compute: (key: K) => PromiseOrValue<V>,
1720
): PromiseOrValue<V> {
1821
const existing = cache.get(key);
1922
if (existing) {
2023
return existing;
2124
}
22-
const resultOrPromise = compute(key);
23-
cache.set(key, resultOrPromise);
25+
let resultOrPromise = compute(key);
2426
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) => {
2629
cache.set(key, result);
2730
return result;
2831
});
2932
}
33+
cache.set(key, resultOrPromise);
3034
return resultOrPromise;
3135
}
32-
33-
export type CacheLike<K, V> = {
34-
get(key: K): V | undefined;
35-
set(key: K, value: V): void;
36-
};

0 commit comments

Comments
 (0)