Skip to content

Instantly share code, notes, and snippets.

@cherihung
Created February 20, 2022 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cherihung/be7cbe45b0d9f11b48ea254f9bc49a74 to your computer and use it in GitHub Desktop.
Save cherihung/be7cbe45b0d9f11b48ea254f9bc49a74 to your computer and use it in GitHub Desktop.
let cache;
const TTL = 1500;
const callApi = () => {
return new Promise((res, rej) => res('1234'))
}
async function getData() {
if (cache) return cache;
try {
const newProm = await callApi();
console.log('get new result', newProm);
cache = newProm;
setTimeout(() => {
cache = undefined;
console.log('resetting cache', cache)
}, TTL)
} catch (err) {
console.log('caught error', err)
cache = undefined;
}
// const newProm = callApi();
// newProm
// .then((result) => {
// console.log('get new result', result);
// setTimeout(() => {
// cache = undefined;
// console.log('resetting cache')
// }, TTL)
// return result;
// })
// .catch((err) => {
// console.log('caught error', err);
// cache = undefined;
// })
// cache = newProm;
return cache;
}
(async () => {
setInterval(async () => {
const data = await getData();
console.log('get data', data)
}, 500)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment