0

I am having a very difficult time getting the timing of a simple counting process down.

When I use console.log and alerts to debug, it seems that the code runs randomly - not in the order it appears in the function.

I'm creating a Google Extension and using sync storage to store settings and retrieve them to update values for the user.

For instance, I'm trying to stuff a string into "localBody" so I can then count the words in the string.

So first up in background.js is a listener that fires when a specific sync variable is changed...and it pulls a value from sync storage:

chrome.storage.onChanged.addListener(function(changes, sync) {if (changes["Clabel"]){alert("Label Changed - start listener update...");
//Get body, label, group from Sync Storage
chrome.storage.sync.get('Cbody', function (results) {   
localBody = results.Cbody;
console.log("first pulling body string from sync storage" + localBody);
});

Later in the code localBody is sent off to a sub that counts words in the string:

wordCount = wordCount + countWords(localBody);              //Update total word count with latest addition

This code fails ("extensions::uncaught_exception_handler:8 Error in event handler for storage.onChanged: TypeError: Cannot read property 'replace' of undefined") and the console shows that it runs BEFORE the sync storage "get" command.

I have tried to do this basic task a zillion ways and I continually run into the unpredictability of pulling from sync storage. I don't know how to get around this - I need to pull a value and modify it, then stuff it back into sync storage.

11teenth
  • 1,853
  • 1
  • 15
  • 28
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – rsanchez Mar 15 '16 at 04:36

1 Answers1

0

Okay, for the bozos like me who are blundering along trying to build Google Extensions with only cursory knowledge of javascript...

The "Get" process is asynchronous. So you need to use callbacks to control when the value you want will be available.

This is a good explanation - I used the example code verbatim: Chrome.storage.sync.get not storing value in local variable

Community
  • 1
  • 1
11teenth
  • 1,853
  • 1
  • 15
  • 28