util-helpers
Version:
41 lines (38 loc) • 1.24 kB
JavaScript
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 };