Could someone explain to me what’s wrong with checkX()‘s scope? What I’m suspecting that’s wrong is the anonymous function somehow blocks it but I’m not sure how to bypass that.
storage = chrome.storage;
function checkX(){
var x = false;
storage.sync.get(function(data){
if(data.x == true){
x = true;
console.log(x); // << x : true
}
});
console.log(x); // << x : false
return x;
}
console.log result order:
x : false
x : true
2 things that might -and probably will- throw you:
getmethod, as used by you is asynchronous, your IIFE returns prior to the passed callback function is being executed, so it’ll return the value ofxbefore the callback changes it anyhow.Edit:
The
getmethod is just a getter, fair enough, however there is a major difference betweenchrome.storage.sync.get, which gets the data using google sync, andchrome.storage.local.get, which is (almost) the same thing as using thelocalStorageobject, with the added benefits of events. At least, that’s what Google’s docs are telling me at first glance?From the comments below:
The issue here is how and when JS calls the callback function. Even though the getter the OP uses is getting local data, the IIFE has to return first, before JS, being single threaded, can call the callback. That’s why the IIFE returns
false.