I've been using a promise to return a value from local storage in a Chrome extension. It turns out that the promise returns a stale value if LOGGED_IN
changes.
export const loggedIn = new Promise(resolve =>
chrome.storage.local.get('LOGGED_IN', result => {
resolve(result['LOGGED_IN'] === 'USER_IS_LOGGED_IN');
}),
);
However this issue doesn't happen if I wrap the promise in a function.
export const loggedIn = () => new Promise(resolve =>
chrome.storage.local.get('LOGGED_IN', result => {
resolve(result['LOGGED_IN'] === 'USER_IS_LOGGED_IN');
}),
);
sendMessage doesn't have this issue. I can use it directly and it never returns a stale value:
const getTabId = chrome.runtime.sendMessage({ message: 'get-tab-it' });
Why do the two behave differently? Does sendMessage not also return a promise?
The issue is not with any chrome
APIs. It is due to the way you're initialising variable loggedIn
.
loggedIn
is a const
variable which is set to a Promise
object. This Promise
object will only be resolved once when you do await loggedIn
and at that time value of key LOGGED_IN
will be fetched from the localStorage
.
Wrapping the promise in a function ensures that every time you call the function, a new Promise
object is returned and the value of the key is fetched from localstorage each time.