sindresorhus / memoize

Memoize functions - an optimization technique used to speed up consecutive function calls by caching the result of calls with identical input

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cache maxAge is evaluated wrong for async functions

krystofwoldrich opened this issue · comments

I've noticed, that when memoizing long lasting async functions, the maxAge is evaluated relative to the moment when function call started. But in case of sync functions it is evaluated relative to the moment the function was resolved.

Expected: Sync functions as is. Async functions (functions that return promise) maxAge should be evaluated relative to when promise is resolved.

Current: Async functions maxAge is evaluated relative to the moment when Promise is returned. (Not resolved, as I would expect!)

Fix: Dirty fix is add await, but then all memoized function will be async. Clean fix is to change beaviour base on function return type. If Promise then wait till it's resolved. Else as is now.

I really appriciate your work, it's great library, just I can't use it because of this unexpected behaviour. Or if I miss understood something and it's working correctly I'm in advance sorry.

mem caches the result of the function, which in this case is just a (Promise) object. What the object does isn't important as far as mem is concerned. What you're looking for is p-memoize, which wraps mem. You can probably open an issue there (or hope that Sindre can transfer this one to that repo first)

I understand that the function returns Promise so the behaviour is correct for sync code. But not for async, where unresolved Promise is just "not finished" function.

And since p-memoize is build on top of mem the same unexpected behaviour occours there too.

unresolved Promise is just "not finished" function.

No, Promises are objects that are returned immediately. mem stores what the function returns, which is an object. If you want Promise-aware memoization, p-memoize exists for that reason.

And since p-memoize is build on top of mem the same unexpected behaviour occours there too.

I didn't say that it works there, but that it can be asked/reported there as it would be more appropriate

Okay. Then the mention in doc about works fine with async fucntions should dissapear.

I was asking about this, because in JS async functions and functions returning Promise, could be looked at as the same. But their intention is very different (in one promsie is the result, in one the resolved Promise is the wanted result), I think you would agree. But this library takes it as the same.