You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The current memoize functions cache raw Promises without evaluating them. This is an issue, because I do not want to cache rejected Promises.
Reproduction:
import{memoizeO}from'@thi.ng/memoize'functionrejectAfterDelay(ms?: number){returnnewPromise((_,reject)=>setTimeout(reject,ms))}asyncfunctiontest(){constmemoizedAsyncFn=memoizeO(async(delay: number)=>{console.log('executing')awaitrejectAfterDelay(delay)})try{awaitmemoizedAsyncFn(2000)}catch{console.log('Failure 1')}try{awaitmemoizedAsyncFn(2000)}catch{console.log('Failure 2 without delay, because the same Promise got re-evaluated')}}test()
Solution:
Make asynchronous variants for all memoization functions that skip caching when the Promise is rejected.
Reason:
Throwing an error synchronously in memoize functions causes the caching to be skipped. The same thing does not happen for rejected Promises. This is fine if reusing the same failed Promise is intentional, but I would assume that for most use cases this is not the desired outcome.
Example workaround:
I wrote a workaround async variant of memoizeO to showcase the desired behavior:
importtype{NumOrString}from'@thi.ng/api'import{memoizeO}from'@thi.ng/memoize'typeMemoize<AextendsNumOrString,B>=Parameters<typeofmemoizeO<A,B>>typeMemoizeFunction<AextendsNumOrString,B>=Memoize<A,Promise<B>>[0]typeMemoizeCache<AextendsNumOrString,B>=Memoize<A,Promise<B>>[1]/** * Memoizes the result of an asynchronous function. Caching is skipped when errors are raised. * * @param fn * @param cache */exportfunctionmemoizeAsync<AextendsNumOrString,B>(fn: MemoizeFunction<A,B>,cache?: MemoizeCache<A,B>,){cache=cache ?? {}constmemoized=memoizeO(fn,cache)returnasync(x: A)=>{try{returnawaitmemoized(x)}catch(error){deletecache[x]throwerror}}}
The text was updated successfully, but these errors were encountered:
The current memoize functions cache raw Promises without evaluating them. This is an issue, because I do not want to cache rejected Promises.
Reproduction:
Solution:
Make asynchronous variants for all memoization functions that skip caching when the Promise is rejected.
Reason:
Throwing an error synchronously in memoize functions causes the caching to be skipped. The same thing does not happen for rejected Promises. This is fine if reusing the same failed Promise is intentional, but I would assume that for most use cases this is not the desired outcome.
Example workaround:
I wrote a workaround async variant of
memoizeO
to showcase the desired behavior:The text was updated successfully, but these errors were encountered: