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

chrome extension chrome.storage how to do a lot of get and set the same time and avoid race condition?

本文关键字:设置 获取 条件 竞争 storage chrome 扩展 何同时 Chrome      更新时间:2023-09-26

我从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。设置和获取本地存储是同步/阻塞的,因此无需担心争用条件。

然后,您可以决定一些空闲时间/事件以localStoragechrome.storage同步。

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