I am quite new to promises and I think the implementation is quite weird also ;-)
I am working on a manifest 3 extension and need to make calls to chrome.storage.session.get and chrome.storage.local.get synchronously without callback seen from the caller side.
This is because a lot of the code in the big project is used both in the extension but also on normal web pages etc and it will be a nightmare to rewrite everything and test it again.
But my implementation test with async/await does not work as expected.
I have this function
const getObjectFromSessionStorage = async function(key)
{
return new Promise((resolve, reject) =>
{
try
{
chrome.storage.session.get(key, function(value)
{
if (chrome.runtime.lastError)
reject(chrome.runtime.lastError);
if(typeof(value[key]) === 'undefined')
reject('undefined:' + key);
resolve(value[key]);
});
}
catch (ex)
{
reject(ex);
}
});
};
That I try to call synchronously in this function:
const getItemPromise = (session, key) =>
{
let returnvalue;
(async function ()
{
if(session)
{
returnvalue = await getObjectFromSessionStorage(key);
}
else
{
returnvalue = await getObjectFromLocalStorage(key);
}
}());
//debugger;
return returnvalue;
But it only work if I stop in the debugger just before "return returnvalue;" If I do not it will return right away.
chrome.storage.session.set({'TEST': 'HELLO'}, () =>
{
if (chrome.runtime.lastError)
console.log(chrome.runtime.lastError);
chrome.storage.session.get('TEST', (value) =>
{
if (chrome.runtime.lastError)
console.log(chrome.runtime.lastError);
console.log(value);
});
console.log(getItemPromise(true, 'TEST'));
});
E.g without debugger stop console.log(value); is returned last and console.log(getItemPromise(true, 'TEST')); is returned first with undefined as result. With debugger stop console.log(getItemPromise(true, 'TEST')); is returned last and with the correct content.
I do not understand why - hope somebody can help me out here