zeeshan zeeshan - 3 months ago 12
Javascript Question

Get return value from async function in Javascript

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;
}
});
}

Answer

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();
        }
    });
}
Comments