我从chrome.storage.local.get
获取一个对象,然后我想通过在回调中使用chrome.storage.local.set
来更新该对象。
如果多次执行回调,则会发生争用条件。我该怎么做才能避免这种情况?
我知道可以通过jQuery.defer
来解决,但是有什么方法可以进行原子更新吗?或者有什么改进我的代码的建议?
下面是一个非常简单的例子:
chrome.tabs.onCreated.addListener(function(tab){//a lot of at the same time
//just test
chrome.storage.local.get(null, function(items) {
if(!items.test){
items.test=[];
}
items.test.push(something);
chrome.storage.local.set(items,function(){});
console.log('a'+JSON.stringify(items));
});
});
一种解决方案是将localStorage
与chrome.storage
结合使用。
您可以将localStorage
用于听众的所有频繁get
和set
。设置和获取本地存储是同步/阻塞的,因此无需担心争用条件。
然后,您可以决定一些空闲时间/事件以localStorage
与chrome.storage
同步。
假设用户将在任何时候在一台计算机上使用此扩展,这将起作用。