UNPKG

util-helpers

Version:

一个基于业务场景的工具方法库

41 lines (38 loc) 1.24 kB
import { __assign } from 'tslib'; import { Cache } from 'cache2'; import { isString } from 'ut2'; var AsyncMemo = (function () { function AsyncMemo(options, ns) { if (ns === void 0) { ns = 'uh_async_memo'; } this.promiseCache = {}; this.cache = new Cache(ns, options); } AsyncMemo.prototype.run = function (asyncFn, key, options) { var _this = this; if (!key || !isString(key)) { return asyncFn(); } var opts = __assign({ persisted: true }, options); if (opts.persisted) { var data = this.cache.get(key); if (data) { return Promise.resolve(data); } } if (!this.promiseCache[key]) { this.promiseCache[key] = asyncFn() .then(function (res) { delete _this.promiseCache[key]; _this.cache.set(key, res, opts.ttl); return res; }) .catch(function (err) { delete _this.promiseCache[key]; return Promise.reject(err); }); } return this.promiseCache[key]; }; return AsyncMemo; }()); export { AsyncMemo as default };