chrome.storage API is asynchronous - it does not return it directly, but passes it as an argument to the callback function. The function call itself always returns undefined .
This is often used to allow other methods to start without having to wait for something to respond or complete - an example of this is setTimeout (the only difference is that it returns a timer value, not an undefined ).
For example, take this:
setTimeout(function () { alert(1); }, 10000); alert(0);
Since setTimeout is asynchronous, it will not stop all code until the whole function completes, but will return at the beginning, calling only the function when it will be completed later - thatโs why 0 goes up to 1.
For this reason, you cannot just do something like:
// "foo" will always be undefined var foo = asyncBar(function (e) { return e; });
Generally, you should put what you want to do in your callback (the function that is called when the asynchronous function is completed). This is a fairly common way to write asynchronous code:
function getValue(callback) { chrome.storage.sync.get("value", callback); }
You can put all of your code in a callback - nothing prevents you from doing this. Therefore, instead of doing the following:
console.log(getValue()); // typical synchronous method of doing something
This would probably be a better idea:
// how it would be done in asynchronous code getValue(function (value) { console.log(value); });
Qantas 94 Heavy
source share