async-cacheify
Wrapper for async functions.
Usage
We can expect expensiveFunction
is something we don't want to run very often. So we wrap it with this library, for the lifetime of the application it will only run the first time.
const cacheify = ; { return await ;} const cheapFunction = ; const results = await Promiseall ;
We are able to run cheapFunction
a lot for free.
Parameters
You can use parameters as you would expect.
Any parameters you pass create a new cache only relevant for when those specific parameters are used again. In the following example the function will run twice, one time with 'x', 'y'
and then with 'q', 'y'
.
const cacheify = ; { return await ;} const cheapFunction = ; const result1 = await ;const result2 = await ;const result3 = await ;const result4 = await ;
Expiry
It is possible to set a cache expiry so that the function will execute again whenever the data gets old. The following example demonstrates a 1000ms cooldown.
const cacheify = ; { return await ;} const cheapFunction = ;
Parallel function calls
By setting the cache expiry to 0
you will not have the benefit of a long running cache. However if the function is run more than once before the first invocation finishes they will still share the result without it running multiple times.
const cacheify = ; { return await ;} const cheapFunction = ; const result1 result2 = await Promiseall ;
Flush
It is possible to force the function to run by using flush
.
The example below flushes the cache twice and runs the function three times. If there is already an invocation running that invocation will finish in the background and complete as normal but new invocations will wait for the new one.
const cacheify = ; { return await ;} const cheapFunction = ; const result1 = await ;cheapFunction;const result2 = await ;const result3 = await ;cheapFunctionconst result4 = await ;
Flush all
You can clear the cache for the entire function and not just specific parameters by using flushAll
.
const cacheify = ; { return await ;} const cheapFunction = ; const result1 = await ;const result2 = await ;cheapFunction;const result3 = await ;const result4 = await ;cheapFunction;
Errors
Any error thrown does not store a cache. Therefore further invocations will keep trying to get it to work until there is a cache again.
const cacheify = ; { throw 'Kabooooooom!';} const cheapFunction = ; try await Promiseall ; catch e console; // Kabooooooom!try await ; catch e console; // Kabooooooom!
Contribute
Sure!