I have this code to get some data from an API:
const data = async () => {
const apiResponse = await dataFromAPI();
return apiResponse;
}
The apiResponse
will always be the same for a session where this code is run. I chose this design because I would like the opportunity to chain multiple functions to the API.
I added a cache variable to short-circuit future requests.
let dataCache;
const data = async () => {
if (dataCache) return dataCache;
const apiResponse = await dataFromAPI();
dataCache = apiResponse;
return dataCache;
}
However, calling data()
twice in succession will make still two API requests.
data().then(response => console.log(response))
data().then(response => console.log(response))
This makes one API request, then uses the cache variable:
data().then(response => console.log(response))
setTimeout(() => {
data().then(response => console.log(response))
}, 100)
How can I design a singleton for this?