Makes a function cache its return value and combine concurrent executions by caching it's result and not executing it again if it still busy acquiring the result. A cache is identified by the arguments used to call the function.
Please note that the context of the resolver function provided loses its context if not first bound with context.
Parameters:
Name |
Type |
Description |
resolver |
function
|
The function to make a LazyLoader out of, should in most cases return a Promise but can do with just returning the result |
lifetime |
Number
|
defaults to 6000, amount of ms to cache a value after it has been acquired |
Returns:
The lazily loading function
-
Type
-
function
Example
import LazyLoader from '../path/to/LazyLoader';
function fn (arg1, arg2) {
return new Promise(resolve => {
// ... do some async stuff ...
resolve(result);
});
};
const lazyFn = LazyLoader(fn, 6000);
// executes fn, no caches for arguments [1, 2] exist
lazyFn(1, 2)
.then(...);
// doesn't execute fn if executed within 6000ms after the data for arguments [1, 2] was acquired
lazyFn(1, 2)
.then(...);
// doesn't execute fn if executed within 6000ms ...
lazyFn(1, 2)
.then(...);
// doesn't execute fn if executed within 6000ms ...
lazyFn(1, 2)
.then(...);
// executes fn, because arguments [1, 3] dont have a cached value
lazyFn(1, 3)
.then(...);