Bjorn Beishline
Bjorn Beishline

Reputation: 103

Callback returns undefined with chrome.storage.local.get

I keep having the same problem with my code, which I've been constenly trying to fix. I have a save and read function in my program. This following code is a shrinked version of my code.

functions.js

// Reads data from ChromeStorage
function read(key) {
    if(key != null) {
        chrome.storage.local.get(key, function (obj) {
            return obj;
        });
    }
}

// Saves data to ChromeStoarge
function save(key, obj) {
    var jsonfile = {};
    jsonfile[key] = obj;

    chrome.storage.local.set(jsonfile, function () {
        console.log('Saved');
    });
}

popup.html

<!DOCTYPE html>        
<html>
    <head>
        <title>Habit Breaker</title>
        <link rel="stylesheet" type="text/css" href="css/main.css">
    </head>
    <body>

        <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
        <script type="text/javascript" src="js/functions.js"></script>
        <script type="text/javascript" src="js/popup.js"></script>

    </body>
</html>

popup.js

save("Test", "Hello");

read("Test");

manifest.json

{
    "manifest_version": 2,

    "name": "Problem",
    "description": "This extension has a huge problem",
    "version": "1.0",

    "permissions": [
        "storage"
    ],

    "browser_action": {
        "default_popup": "popup.html"
    }

}

When I call the save function all runs as expected, the data is successfully stored. But when I call the read function it returns an undefined.

The strange part is when instead of returning the obj in the save function, I console.log() it and it returns my expected value.

I'm starting to run out of ideas, and I did many hours of reasearch. If anyone has a clue, it would be appreciated.

Upvotes: 4

Views: 1936

Answers (1)

Denis L
Denis L

Reputation: 3292

As Iván said, the chrome.storage API is asynchronous, you can handle it with couple ways:

1.Callback function

function read(key, callback) {
    if(key != null) {
        chrome.storage.local.get(key, function (obj) {
            callback(obj);
        });
    }
}

// Usage
read("test", function(val) {
  // val...
})

2.Promise

function read(key) {
    return new Promise((resolve, reject) => {
        if (key != null) {
            chrome.storage.local.get(key, function (obj) {
                resolve(obj);
            });
        } else {
            reject(null);
        }
    });
}

// 1. Classic usage
read('test')
    .then(function (val) {
        // val...
    })
    .catch(function () {
        // looks like key is null
    });

// 2. Use async/await
var val = await read(test);
console.log(val);

Upvotes: 4

Related Questions