2

I have a function that is checking for a stored value through chrome.storage.sync.get and inserting a CSS file upon existence of said stored value.

I realize chrome.storage.sync.get is an async function and the return value is not passing back as expected to the makeAggressive() function. However, I don't know how else to write this code to get the result of if (result == 'aggressive') passed to makeAggressive().

How can I retrieve the stored value, check its value and return the result to the calling function?

chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
    if (info.status == 'complete') applyCSS(tab);
});

function applyCSS(tab) {
    var tabUrl = tab.url;

    if (makeAggressive()) {
        chrome.tabs.insertCSS(tab.id, {
            file: "aggressive.css"
        });
    }
}

function makeAggressive() {
    chrome.storage.sync.get(function(items) {
        var result = items.intensityLevel;
        if (result == 'aggressive') {
            return true;
        }
  });
}
zeeshan
  • 719
  • 2
  • 7
  • 13
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Makyen Aug 06 '16 at 20:53

1 Answers1

2

Simply pass a callback into the async function.
The callback shall be called once the asynchronous activity is completed.

async_function(function() {
    // do something after async_function completes and invokes this callback
});

function async_function(callback) {
    something_async(function(result) {
        callback(result);
    });
}

In your case:

function applyCSS(tab) {
    var tabUrl = tab.url;

    makeAggressive(function() {
        chrome.tabs.insertCSS(tab.id, {
            file: "aggressive.css"
        });
    });
}

function makeAggressive(callback) {
    chrome.storage.sync.get(function(items) {
        var result = items.intensityLevel;
        if (result == 'aggressive') {
            callback();
        }
    });
}
wOxxOm
  • 65,848
  • 11
  • 132
  • 136