Skip to content

Instantly share code, notes, and snippets.

@arkadijs
Last active October 20, 2022 13:25
Show Gist options
  • Save arkadijs/fc8bc748cbb32a6fc47bb2b78ad9409d to your computer and use it in GitHub Desktop.
Save arkadijs/fc8bc748cbb32a6fc47bb2b78ad9409d to your computer and use it in GitHub Desktop.
Serialize and Cache JavaScript Promise
const defaultTtl = 60 * 60;
const validAtLeast = 10 * 1000;
const retry = 5 * 1000;
function cache(retrieve) {
const context = {
expireAt: 0,
promise: null,
get() {
const {expireAt, promise} = this;
const now = Date.now();
if (promise && (expireAt === 0 || now + validAtLeast < expireAt)) {
return promise;
}
this.expireAt = 0;
const token = setTimeout(() => {
this.promise = null;
}, retry);
this.promise = retrieve().then((obj) => {
clearTimeout(token);
this.expireAt = now + ((obj.ttl || defaultTtl) * 1000);
return obj;
});
return this.promise;
}
};
return context.get.bind(context);
}
const applicationTokens = cache(() => api.post(`/apps/${appId}/login`, {highPrivRoleId, lowPrivRoleId}));
const tokens = await applicationTokens();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment