Created
December 2, 2019 07:51
-
-
Save compulim/f4fc6f7c616f95a123e7f864b128a5eb to your computer and use it in GitHub Desktop.
Create memoized fetch credentials
This file contains hidden or 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 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