javascript 回调返回未定义的 chrome.storage.sync.get
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18699075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Callback returns undefined with chrome.storage.sync.get
提问by crzyonez777
I'm building a Chrome extension and I wrote this code.
我正在构建一个 Chrome 扩展程序,我编写了这段代码。
var Options = function(){};
Options.prototype = {
getMode: function(){
return chrome.storage.sync.get("value", function(e){
console.log(e); // it prints 'Object {value: "test"}'.
return e;
});
},
setMode: function(){
chrome.storage.sync.set({"value": "test"}, function(e) {
})
}
}
var options = new Options();
options.setMode();
console.log(options.getMode()); // it prints 'undefined'.
I expected it to print
我希望它打印
Object {value: "set up"}
when I call options.getMode()
, but it prints undefined
.
当我打电话时options.getMode()
,但它打印undefined
。
Does anyone know how to fix this problem?
有谁知道如何解决这个问题?
回答by Qantas 94 Heavy
The chrome.storage
API is asynchronous- it doesn't return it directly, rather passing it as an argument to the callback function. The function call itself always returns undefined
.
该chrome.storage
API是异步的-它并不直接返回它,而是将它作为参数传递给回调函数。函数调用本身总是返回undefined
。
This is often used to allow other methods to run without having to wait until something responds or completes - an example of this is setTimeout
(only difference is that it returns a timer value, not undefined
).
这通常用于允许其他方法运行而不必等到某事响应或完成 - 一个例子是setTimeout
(唯一的区别是它返回一个计时器值,而不是undefined
)。
For example, take this:
例如,拿这个:
setTimeout(function () { alert(1); }, 10000);
alert(0);
Because setTimeout
is asynchronous, it will not stop all code until the entire function completes, rather returning initially, only calling a function when it is completed later on - this is why 0 comes up before 1.
因为setTimeout
是异步的,它不会在整个函数完成之前停止所有代码,而是最初返回,仅在稍后完成时调用函数 - 这就是为什么 0 在 1 之前出现。
For this reason, you cannotsimply do something like:
因此,您不能简单地执行以下操作:
// "foo" will always be undefined
var foo = asyncBar(function (e) { return e; });
Generally, you should put what you want to do in your callback (the function that is called when the asynchronous function is completed). This is a fairly common way of writing asynchronous code:
一般来说,你应该把你想做的事情放在你的回调中(异步函数完成时调用的函数)。这是编写异步代码的一种相当常见的方式:
function getValue(callback) {
chrome.storage.sync.get("value", callback);
}
You could place an entire portion of your code inside the callback - there's nothing stopping you from doing so. So instead of doing the following:
您可以将整个代码部分放在回调中 - 没有什么可以阻止您这样做。因此,不要执行以下操作:
console.log(getValue()); // typical synchronous method of doing something
This would probably be a better idea:
这可能是一个更好的主意:
// how it would be done in asynchronous code
getValue(function (value) {
console.log(value);
});
回答by Taohidul Islam
Chrome storage APIis asynchronous and it uses callback
, that's why you're getting this behavior.
Chrome 存储 API是异步的,它使用callback
,这就是您得到这种行为的原因。
You can use Promise
API to overcome this asynchronous issue, which is simpler and cleaner. Here is an example:
您可以使用Promise
API 来克服这个异步问题,它更简单、更清晰。下面是一个例子:
async function getLocalStorageValue(key) {
return new Promise((resolve, reject) => {
try {
chrome.storage.sync.get(key, function (value) {
resolve(value);
})
}
catch (ex) {
reject(ex);
}
});
}
const result = await getLocalStorageValue("my-key");
回答by fmsf
The chrome.storage.sync.get
is called asynchronously, that's why you have to pass it a callback, so that it is executed in the future.
该chrome.storage.sync.get
异步调用,这就是为什么你必须通过它的回调,使得它在将来执行。
When you try to print the returned value of getMode
you are printing the return value of whatever chrome.storage.sync.get
returns after queuing the asynchronous call to be executed.
当您尝试打印您的返回值时,getMode
您正在打印将chrome.storage.sync.get
要执行的异步调用排队后返回的任何返回值。
This is a common mistake people do in javascript, while they are learning to use asynch calls.
这是人们在 javascript 中经常犯的错误,而他们正在学习使用异步调用。