UNPKG

vtils

Version:

一个面向业务的 JavaScript/TypeScript 实用程序库。

37 lines 1.09 kB
/** * 异步函数执行缓存。 * * @param asyncFn 异步函数 * @param options 选项 */ export function asyncMemoize(asyncFn, options) { if (options === void 0) { options = {}; } var _options = options, _options$cacheKey = _options.cacheKey, cacheKey = _options$cacheKey === void 0 ? function () { return arguments.length <= 0 ? undefined : arguments[0]; } : _options$cacheKey, cacheTTL = _options.cacheTTL; var cache = new Map(); var call = function call() { var _cacheKey = cacheKey.apply(void 0, arguments); var cacheValue = cache.get(_cacheKey); var currentMs = Date.now(); if (cacheValue && (cacheValue.expiredAt ? currentMs < cacheValue.expiredAt : true)) { return cacheValue.value; } var cacheValueNew = asyncFn.apply(void 0, arguments); cacheValueNew.catch(function () { return cache.delete(_cacheKey); }); cache.set(_cacheKey, { value: cacheValueNew, expiredAt: cacheTTL ? currentMs + cacheTTL : 0 }); return cacheValueNew; }; call.cache = cache; return call; }