Reputation: 15979
I have a small problem, due to my lack of experiance with JS ...
I have a function in my file , which is logging to console correctly, but somehow, not returning same value it logged ( or maybe I do not know how to pull it ..)
function getStoragex() {
chrome.storage.sync.get('alertsOn', function(data) {
var optionShowAlertsx = data;
console.info("This is logging ok" + optionShowAlertsx.alertsOn);
return optionShowAlertsx.alertsOn;
});
}
The logging is :
DATA true
Later on, I have this ( inside another function )
var optionShowAlerts = getStoragex();
console.info("This is logging undefined " + optionShowAlerts);
What am I doing wrong ??
Upvotes: 0
Views: 61
Reputation: 1598
Your return
statement return value to it chrome.storage.sync.get
method 2nd parameter itself. it will not return to getStoragex() method.
try this
function getStoragex() {
var optionShowAlertsx;
chrome.storage.sync.get('alertsOn', function(data) {
optionShowAlertsx = data;
console.info("This is logging ok" + optionShowAlertsx.alertsOn);
});
return optionShowAlertsx.alertsOn
}
var optionShowAlerts = getStoragex();
console.log("This is logging undefined " + optionShowAlerts);
Upvotes: 1
Reputation: 1075337
Your return
statement is inside the anonymous function you're passing to chrome.storage.sync.get
. Your getStoragex
function never issues a return
and so a call to it gets the result undefined
.
If chrome.storage.sync.get
is a synchronous function (which it seems like it might be from the name), you can do this:
function getStoragex() {
var rv;
chrome.storage.sync.get('alertsOn', function(data) {
var optionShowAlertsx = data;
console.info("This is logging ok" + optionShowAlertsx.alertsOn);
rv = optionShowAlertsx.alertsOn;
});
return rv;
}
(That bracing style is unfamiliar to me, apologies if I've messed it up.)
Edit: It looks to me as though the sync
in that name doesn't have to do with the function being synchronous or asynchronous, but rather with data syncing.
If it's asynchonous, then you can't return the result from getStoragex
because getStoragex
returns before the result is available. In that case, you can accept a callback that you, um, call back with the result when you have it:
function getStoragex(callback) {
chrome.storage.sync.get('alertsOn', function(data) {
var optionShowAlertsx = data;
console.info("This is logging ok" + optionShowAlertsx.alertsOn);
callback(optionShowAlertsx.alertsOn);
});
}
Alternately, promises are gaining a lot of popularity at the moment. You might look into using one of those (there are several implementations available). The result will still be asynchronous if chrome.storage.sync.get
is asynchronous, though.
Upvotes: 1