@@ -13,14 +13,16 @@ interface MemoizeEntry<V> {
1313 expiresAt ?: number
1414}
1515
16- export function memoize < P , V > ( fn : ( params : P ) => V , options : MemoizeOptions < P > = { } ) : ( params : P ) => V {
16+ type MemoizeReturn < R > = R extends Promise < infer V > ? Promise < V | undefined > : R | undefined
17+
18+ export function memoize < P , V > ( fn : ( params : P ) => V , options : MemoizeOptions < P > = { } ) : ( params : P ) => MemoizeReturn < V > {
1719 const {
1820 getKey = String ,
1921 ttl = CACHE_TTL_ONE_DAY ,
2022 } = options
2123
2224 const cache = new Map < MemoizeKey , MemoizeEntry < V > > ( )
23- const pending = new Map < MemoizeKey , V > ( )
25+ const pending = new Map < MemoizeKey , Promise < any > > ( )
2426
2527 function get ( key : MemoizeKey ) : Awaited < V > | undefined {
2628 const entry = cache . get ( key )
@@ -40,7 +42,7 @@ export function memoize<P, V>(fn: (params: P) => V, options: MemoizeOptions<P> =
4042 } )
4143 }
4244
43- return function cachedFn ( params : P ) : V {
45+ return function cachedFn ( params : P ) {
4446 const key = getKey ( params )
4547
4648 const hit = get ( key )
@@ -62,10 +64,10 @@ export function memoize<P, V>(fn: (params: P) => V, options: MemoizeOptions<P> =
6264 . catch ( ( ) => cache . get ( key ) ?. value )
6365 . finally ( ( ) => {
6466 pending . delete ( key )
65- } ) as V
67+ } ) as any
6668 pending . set ( key , promise )
6769 return promise
68- } else {
70+ } else if ( result !== undefined ) {
6971 set ( key , result as Awaited < V > )
7072 return result
7173 }
0 commit comments