![](/img/trans.png)
[英]chrome extension chrome.storage how to do a lot of get and set the same time and avoid race condition?
[英]How do you set and get values with Chrome.Storage?
我正在尝试做一个非常简单的设置,并使用chrome.storage.local使用Google Chrome扩展程序进行检索
我有部分要设置:
chrome.storage.local.set({"myValue": "All the data I need"});
我只是不明白如何检索它。
alert(chrome.storage.local.get("myValue"));
我已阅读https://developer.chrome.com/extensions/storage让我感到困惑的部分是为什么应该将某个功能作为storage.local.get的一部分
你快到了。 要检索它,您需要实现get()的回调部分,因为Chrome会通过该函数的参数将数据返回给您。 因此,在您的情况下,您将需要以下内容:
chrome.storage.local.get("myValue", function(obj) {
alert(JSON.stringify(obj));
}):
由于JavaScript代码具有事件驱动和单线程性质,因此大多数chrome API(以及大多数JavaScript代码)都使用此异步构造来“返回”值,这与更传统的“函数返回值方法”不同。
使用这种方法,当您调用API函数时,还会将另一个函数(回调函数)传递给它,该函数包含要在API函数完成其处理后执行的代码(在我上面的代码中是带有alert()的函数)。 然后,API函数在完成时会调用回调函数及其操作结果。
要添加到source.rar的正确但简短的答案中:
您的问题也始于对set
如何工作的误解。 set
和get
都是异步的,因此执行如下所示:
// 1. Suppose the stored value for A is "a"
chrome.storage.local.set({A:"b"});
// 2. The stored value for A is still "a"
发生这种情况是因为set
不会立即执行任何操作,只是将值的实际设置添加到JavaScript的执行队列中。
您也可以为set
添加一个回调。 设置操作后,它被推入队列:
// 1. Suppose the stored value for A is "a"
chrome.storage.local.set({A:"b"}, function(){
// 3. This will execute after the outer function finishes
// and setting is done; the value for A is "b"
});
// 2. The stored value for A is still "a"
现在,这将如何工作?
// 1. Suppose the stored value for A is "a"
chrome.storage.local.set({A:"b"}, function(){
// 3. This will execute after the outer function finishes
// and setting is done; the value for A is "b"
});
// 2. The stored value for A is still "a"
chrome.storage.local.get("A", function(data){
// ??
});
// ??
调用set
和get
的外部函数将内容添加到队列中并完成操作; 然后将前两个项目添加到队列中,即set
和它的回调,而另外两个则是get
和它的回调:
// 1. Suppose the stored value for A is "a"
chrome.storage.local.set({A:"b"}, function(){
// 4. This will execute after the outer function finishes
// and setting is done; the value for A is "b"
});
// 2. The stored value for A is still "a"
chrome.storage.local.get("A", function(data){
// 5. This will execute after the outer function finishes
// and everything else is done;
// the value for A is "b" and data.A is "b"
});
// 3. The stored value for A is still "a"
因此,通常您必须使用回调链式执行,即
// part 1
chrome.storage.local.get("A", function(data){
//part 2
chrome.storage.local.get("B", function(data){
// part 3
}
}
有时,您可以通过同时要求两者来简化上述操作:
// part 1
chrome.storage.local.get(["A", "B"], function(data){
//part 2
//part 3
}
通过为chrome.storage
编写自己的同步缓存,可以简化整个chrome.storage
; 但这也不总是很合适。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.