0

I'm having a problem with an array becoming undefined and I can't figure out why.

I declare the variable ul, I then get the array from storage and assign it to ul, if I try to work with it inside the get function it works, I can do whatever I want, if I try to do anything with outside of the get function it just says it's undefined.

function getUserList()
    {
        var ul;
        chrome.storage.local.get({'users':[]}, function(result){ //get user array from storage
            ul = result.users; //get users from result
            console.log(ul); <-this works
        });
        console.log(ul); <- this does not
        hideSubmissions(ul); <- or this
        hideComments(ul); <- or this
    };

getUserList();

I can move everything that uses ul into the get function but I'd like to know why that is necessary, the only thing I can guess at is that it is somehow going out of scope but I don't see how.

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
DasSnipez
  • 2,182
  • 4
  • 20
  • 29
  • 1
    `console.log(ul);` executes before `local.get()` is completed. Just write them inside. This happens because the calls are asynchronous. You'll find more answers on asynchronous on stackoverflow. Here is one to start with http://stackoverflow.com/questions/7779697/javascript-asynchronous-return-value-assignment-with-jquery – Dhiraj Jul 24 '15 at 17:31

1 Answers1

1

The .get function runs asynchronously so when it finishes it calls the completion handler, which then you are setting ul to the result.users.

Whereas, you have already outputted (or tried to) the ul var before you set it.

Just like the comments are saying.

Micaiah Wallace
  • 1,101
  • 10
  • 17