UNPKG

util-helpers

Version:

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

43 lines (39 loc) 1.25 kB
'use strict'; var tslib = require('tslib'); var cache2 = require('cache2'); var ut2 = require('ut2'); var AsyncMemo = (function () { function AsyncMemo(options, ns) { if (ns === void 0) { ns = 'uh_async_memo'; } this.promiseCache = {}; this.cache = new cache2.Cache(ns, options); } AsyncMemo.prototype.run = function (asyncFn, key, options) { var _this = this; if (!key || !ut2.isString(key)) { return asyncFn(); } var opts = tslib.__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; }()); module.exports = AsyncMemo;