Memoize promise-returning & async functions
Useful for speeding up consecutive function calls by caching the result of calls with identical input.
By default, only the memoized function's first argument is considered via strict equality comparison. If you need to cache multiple arguments or cache objects by value, have a look at alternative caching strategies below.
This package is similar to mem but with async-specific enhancements; in particular, it does not cache rejected promises by default (unless the cachePromiseRejection option is set).
$ npm install p-memoize
import pMemoize from 'p-memoize';
import got from 'got';
const memoizedGot = pMemoize(got, {maxAge: 1000});
memoizedGot('https://sindresorhus.com');
// This call is cached
memoizedGot('https://sindresorhus.com');
setTimeout(() => {
// This call is not cached as the cache has expired
memoizedGot('https://sindresorhus.com');
}, 2000);See the Caching strategy for mem.
Returns a memoized version of the given function.
Type: Function
Promise-returning or async function to be memoized.
Type: object
See the mem options in addition to the below option.
Type: boolean
Default: false
Cache rejected promises.
Type: number
Default: Infinity
The milliseconds until the cache expires.
Type: Function
Default: arguments_ => arguments_[0]
Example: arguments_ => JSON.stringify(arguments_)
Determines the cache key for storing the result based on the function arguments. By default, only the first argument is considered.
A cacheKey function can return any type supported by Map (or whatever structure you use in the cache option).
See the caching strategy section in the mem package for more information.
Type: object
Default: new Map()
Use a different cache storage. Must implement the following methods: .has(key), .get(key), .set(key, value), .delete(key), and optionally .clear(). You could for example use a WeakMap instead or quick-lru for a LRU cache.
See the caching strategy section in the mem package for more information.
Clear all cached data of a memoized function.
It will throw when given a non-memoized function.
- p-debounce - Debounce promise-returning & async functions
- p-throttle - Throttle promise-returning & async functions
- More…