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.