I have x number of calls to be made to back-end. Some of them are to same URLs. I am caching the results. But my problem is thatIf I call loadCached immediately twice (or several times) with a same URL, it will actually call fetch twice as well, as cache does not have url before the first fetch is resolved. So, caching works only when one fetch is successfully completed (=resolved). How could I improve the code to wait for the first fetch to be resolved to avoid duplicate query?
function loadCached(url) {
let cache = loadCached.cache || (loadCached.cache = new Map());
if (cache.has(url)) {
return Promise.resolve(cache.get(url)); // (*)
}
return fetch(url)
.then(response => response.text())
.then(text => {
cache[url] = text;
return text;
});
}
I'm using promise.all() to wait for loadCached to resolve.