[英]chrome extension chrome.storage how to do a lot of get and set the same time and avoid race condition?
我從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是同步的/阻塞的,因此無需擔心競爭狀況。
然后,您可以決定一些空閑時間/事件以將localStorage
與chrome.storage
同步。
假設用戶將在任何時候在一台計算機上使用此擴展名,則將可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.