Memoize Async
Memoize the value of any promise or synchronous function.
Generator functions are not supported.
Memoizing the same function with the same arguments while the async operation is still running will result in an undefined result, but you may listen for the result of the event memoizeAsync.operation.complete
from wherever it's called.
Installation
npm install
If you intend to use this in an non-Node based environment, for example a browser, you must also run npm add events
.
Usage
Initialise With Pre-loaded Data
const memoizeAsync = require("@green-code/memoize-async")({foo: "bar", biz: "baz"});
Get and Set
const hello = async (string) => new Promise(resolve => resolve(`Hello ${string}!`));
memoizeAsync.getAndSet(hello, ["world"]).then(console.log);
memoizeAsync.getAndSet(hello, ["Joe"]).then(console.log);
Get All
console.log(memoizeAysnc.getAll());
Delete By Key
memoizeAysnc.deleteByKey('["hello","AsyncFunction","Joe"]');
console.log(memoizeAysnc.getAll());
Clear All
memoizeAysnc.clear();
console.log(memoizeAysnc.getAll());
Listening For Events
const EventEmitter = require("events");
const eventEmitter = new EventEmitter();
eventEmitter.on("memoizeAsync.operation.complete", ({key, value}) => {
});
Event Names
memoizeAsync.operation.start
When the function is invoked but not yet completed.
memoizeAsync.operation.success.unsaved
The function was called successfully and the value was not saved to memory because it is either undefined, null or an empty string. You might want to check the arguments you pass to the function or check the function itself.
memoizeAsync.operation.success.saved
The function was called successfully and the value was saved to memory.
memoizeAsync.operation.fail
The function returned an error.
memoizeAsync.operation.complete
Always fires whether the value was saved or not.
memoizeAsync.get
Fires when getting an item previously memoized in memory.
memoizeAsync.getall
Fires when getting all items memoized in memory.
memoizeAsync.delete
Fires when deleting a memoized item from memory.
memoizeAsync.queue.add
When a function call is added to the queue. This is ensures the same function with the same arguments isn't called twice.
memoizeAsync.queue.remove
When a function is removed fromm the queue.
memoizeAsync.queue.clear
When the queue is cleared.