我的代码一直存在同样的问题,我一直在努力解决这个问题.我的程序中有一个保存和读取功能.以下代码是我的代码的缩小版本.
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"
}
}
当我调用save函数时,所有运行都按预期运行,数据已成功存储.但是当我调用read函数时,它会返回一个未定义的函数.
奇怪的部分是,而不是在save函数中返回obj,我在console.log()它,它返回我期望的值.
我开始没有想法,我做了很多小时的研究.如果有人有线索,我们将不胜感激.
最佳答案 正如Iván所说,chrome.storage API是异步的,您可以通过几种方式处理它:
1.Callback功能
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);