Caching and pre-fetching expiring promises in Javascript

柔情痞子 提交于 2019-12-05 05:00:39

This function will allow me to memoize an async function (with node-like callbacks) returning a promise. However, this approach seems messy and over-engineered to me.

Yes - you already have a function returning a promise, there is no reason to go back to nodebacks.

Is there a simpler solution that I've missed?

A function that returns a promise is just a function that returns some value - a value that can be cached by the memoize function. Simply do

memoize(funcReturningPromise, options)

You understand promises correctly - a promise is a proxy for a value - once it's set it will never change.

The only way around this is to not return the same promise each time - you'd have to return a different promise each time (like your example does). The simplest solution would be to use memoize with promise returning functions (and it'd cache the promise for the value).

If we have a function foo(){ that returns a promise. It's perfectly fine to just memoize that function itself and then use all the tools the library provides.

Note: promisify is expensive and produces a very fast function - you really don't want to call it at runtime. You could simply return new Promise in your code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!