Adonis K. Kakoulidis
Adonis K. Kakoulidis

Reputation: 5133

Return value wrapped around anonymous function in javascript

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

Upvotes: 0

Views: 939

Answers (2)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

2 things that might -and probably will- throw you:

  1. JavaScript is case-Sensitive
  2. the get method, as used by you is asynchronous, your IIFE returns prior to the passed callback function is being executed, so it'll return the value of x before the callback changes it anyhow.

Edit:
The get method is just a getter, fair enough, however there is a major difference between chrome.storage.sync.get, which gets the data using google sync, and chrome.storage.local.get, which is (almost) the same thing as using the localStorage object, 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.

Upvotes: 1

fmsf
fmsf

Reputation: 37137

Javascript is case sensitive. What you are doing is creating a global variable x which is true, while the local variable X remains false.

storage = chrome.storage;

function checkX(){
    var X = false;

    storage.sync.get(function(data){
        if(data.x == true){
            x = true;  <--- global variable
        }
    });

    return x;
}

Another issue would be if the storage.sync.get runs async from the "checkX", which would mean that first you return x and only later on (after you have returned it) will your function be executed. This will happen for sure if storage.sync.get is an ajax call.

Upvotes: 0

Related Questions