Skip to content

Instantly share code, notes, and snippets.

@compulim
Created December 2, 2019 07:51
Show Gist options
  • Save compulim/f4fc6f7c616f95a123e7f864b128a5eb to your computer and use it in GitHub Desktop.
Save compulim/f4fc6f7c616f95a123e7f864b128a5eb to your computer and use it in GitHub Desktop.
Create memoized fetch credentials
const TOKEN_EXPIRE_AFTER = 300000;
// This function will create a memoized fetchCredentials function and reduce the call to the function.
// The memoized result is time-sensitive and will be invalidated after 5 minutes (specified in TOKEN_EXPIRE_AFTER).
const createMemoizedFetchCredentials = () => {
let lastFetch = 0;
let lastPromise;
return () => {
const now = Date.now();
if (!lastPromise || now - lastFetch > TOKEN_EXPIRE_AFTER) {
lastFetch = now;
lastPromise = fetchCredentials().catch(error => {
lastPromise = null;
return Promise.reject(error);
});
}
return lastPromise;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment