planttheidea/micro-memoize

Allow `onCacheHit`, `onCacheAdd` and `onCacheChange` to be `async`

Closed this issue · 4 comments

When isPromise is true and one of those options return a rejected Promise, the moized functions should return that rejected Promise. Otherwise, this would result in an unhandled rejected promise (the error is not propagated).

Forgive me, I'm having a hard time envisioning what you are explaining occurs now and what is expected. Can you write a simple example of this? Even pseudo code would be fine.

My problem is the following.

const mFunc = memoize(func, { 
  isPromise: true,
  async onCacheHit() {
    await doHttpRequest()
  },
})

try {
  await mFunc()
} catch (error) {
  console.log(error)
}

If doHttpRequest() returns a rejected promise, that promise will not propagate from await mFunc().

However, now I am thinking more about it, it does seem like memoizing should be part of the internals of mFunc and should not be exposed to the consumer of mFunc, i.e. it should be handled directly inside onCacheHit instead:

const mFunc = memoize(func, { 
  isPromise: true,
  async onCacheHit() {
    try{
      await doHttpRequest()
    } catch (error) {
      console.log(error)
    }
  },
})

Based on this, the current logic already works. Please let me know what you think, and I will close this issue. Thanks!

Agreed with your determination. The call made in on cache hit is a subsequent operation unrelated to the successful run of the cached function. If that error propagated it would break the original contract because the result of calling the memoized function would not have parity with calling the function normally.

Nonetheless, appreciate the consideration. 😁

Makes sense!