How to wait for asynchronous chrome.storage.local.get() to finish before continuing execution
You need to wait for both callback function that you pass to chrome.storage.local.get(..)
to be executed before you call continueCode()
, also, you can check both storage properties with a single call, here is an example:
function getData() {
chrome.storage.local.get(['key', 'key2'], function(result) {
if (typeof result.key !== 'undefined') {
object1.innerHTML = result.key.val;
}
if (typeof result.key2 !== 'undefined') {
object2.innerHTML = result.key2.val;
}
continueCode();
}
}
Why does chrome.storage.local.get return undefined for the value?
Chrome saves the data under the key you set it as. In your example, you saved it as txt
, so it will be under data.txt
not data.key
.
Check out the docs for some more details https://developer.chrome.com/docs/extensions/reference/storage/#usage
Chrome Extension - Chrome.storage - Why does chrome.storage.sync.get returns undefined?
chrome.storage.sync.get
is an asynchronous method, that's why you need to give a callback to it when it has done getting the storage. So you can't adopt a procedural code structure for that. A solution would be to use a callback structure:
function setStorageKey(key, value){
chrome.storage.sync.set({ key: value });
}
function getStorageKeyValue(key, onGetStorageKeyValue){
chrome.storage.sync.get([key], function(result) {
onGetStorageKeyValue(result.key);
});
}
let value = 10;
setStorageKey("K1", value);
getStorageKeyValue("K1", function(key) {
alert("Set value: "+value+" --- Received value: "+ key);
});
Unable to get array from chrome.storage
Wrap the call to storage in a promise and await it:
function getStorageValuePromise(key) {
return new Promise((resolve) => {
chrome.storage.sync.get(key, resolve);
});
}
await getStorageValuePromise('val');
Related Topics
How to Add Conditional Attribute in Angular 2
Jquery (Or Pure Js) Simulate Enter Key Pressed for Testing
Getting Unexpected Token Export
Redirect a State to Default Substate with Ui-Router in Angularjs
Turning Off Eslint Rule for a Specific Line
Javascript: Formatting a Rounded Number to N Decimals
JavaScript Drag and Drop for Touch Devices
Most Efficient Way to Concatenate Strings in JavaScript
Why Does !New Boolean(False) Equals False in JavaScript
How to Watch for a Route Change in Angularjs
(![]+[])[+[]]... Explain Why This Works
When Is the Body of a Promise Executed
Equivalent of String.Format in Jquery
How to Parse a Time into a Date Object from User Input in JavaScript
How to Get Evaluated Attributes Inside a Custom Directive