Last active
October 20, 2022 13:25
-
-
Save arkadijs/fc8bc748cbb32a6fc47bb2b78ad9409d to your computer and use it in GitHub Desktop.
Serialize and Cache JavaScript Promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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