chrome extension chrome.storage 如何同时进行大量获取和设置并避免竞争条件?

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));
        });    
});

一种解决方案是结合使用 localStoragechrome.storage

您可以将 localStorage 用于听众中所有频繁出现的 getset。设置和获取 localStorage 是 synchronous/blocking 因此无需担心竞争条件。

然后您可以决定一些闲置 time/event 以将 localStoragechrome.storage 同步。

假设用户将在任何时候在一台计算机上使用此扩展程序,这将起作用。