I'm trying to figure out how to correctly use asynchronous functions for the purpose as described below.
<code>
async function commentGrabSwitchboard(){
let prevStored = await checkStorage();
if(IsAmazonFirstProductPage(document)){
if(prevStored == undefined){
collectProductComments();
}else{
console.log("Results retrieved from chrome local storage: \n" + JSON.parse(prevStored));
}
}
}
</code>
This function is designed as a switchboard. It does one of two things - either call collectProductComments or (for now) console log a result - dependant on the return value of the checkStorage function:
<code>
async function checkStorage(){
let key = location.host + location.pathname;
try{
chrome.storage.local.get(key, function(result) {
let returnData = result[key];
return returnData;
});
}catch(err){
console.log("Results for domain: " + key + "could not be retrieved from chrome local storage. Error: " + err);
}
}
</code>
This function checks local storage for a value, and returns that value. If it should find nothing, the return value is undefined. The problem I am encountering is that the script does not wait for checkStorage to resolve after declaring the variable prevStored = checkStorage, and so the if statement "prevStored == undefined" is always true. I have verified that the checkStorage function does return the expected value from local storage.
Could anyone give me some pointers as to how I've done things incorrectly? Any alternative solutions are also welcome. Thanks.
temporary: changes to second function
function checkStorage(){
let key = location.host + location.pathname;
let storageSearched;
let returnData;
try{
chrome.storage.local.get(key, function(result) {
returnData = result[key];
storageSearched = true;
});
}catch(err){
console.log("Results for domain: " + key + "could not be retrieved from chrome local storage. Error: " + err);
storageSearched = false;
}
let promise = new Promise((resolve, reject) => {
if(storageSearched){
resolve(returnData);
}else{
reject();
}
});
promise.then(function(fromResolve){
return fromResolve;
});
}