Having some trouble with a caching system in my code where I'm trying to load the same template quickly. Even though I've tried implementing a basic caching mechanism to only fetch the template if it hasn't been loaded before, I'm struggling with getting the await to actually wait until the function is done.
This is the section of code responsible for loading the template:
var arrContent = []; //array of objects: {"url":"http://...", "content": "<div>..."}
var content = null;
this.loadFile = async function(url){
//Checking if the content has already been loaded
let i = findContentIndex(url);
if(i != null){ // The template already exists, so we just load it from memory
console.log("Cached!");
content = arrContent[i].content;
}else{
//If the content is not in cache, we fetch it from the URL
console.log("Fetching...");
await fetch(url)
.then(function(response){
return response.text();
})
.then(function(response) {
content = response;
arrContent.push({"url": url, "content": content});
})
.catch(
function() {
error => console.log(error);
}
);
console.log("content");
}
}
function findContentIndex(url){
for(let i=0; i<arrContent.length; i++)
if(arrContent[i].url != undefined && arrContent[i].url == url)
return i;
return null;
}
this.render = function(){
//...
}
After running the code multiple times within milliseconds of each other, I end up with an array containing duplicates of the same template URL, even though the code should be preventing duplicates.
Here's how the calls are being made for context:
await Tpl.loadFile(chrome.runtime.getURL("view/widget.html"));
let content = Tpl.render();
The output ends up looking like this:
Fetching...
Fetching...
Fetching...
Fetching...
Fetching...
content
content
content
content
content
Instead of:
Fetching...
content
Cached!
Cached!
Cached!
Cached!
If the entire LoadFile function could execute just once at a time, it would solve the issue I'm facing.
Thank you!