铬扩展chrome.storage如何做很多获取和设置相同的时间,并避免竞争状态? [英] chrome extension chrome.storage how to do a lot of get and set the same time and avoid race condition?

查看:161
本文介绍了铬扩展chrome.storage如何做很多获取和设置相同的时间,并避免竞争状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 chrome.storage.local.get 中获得一个对象,然后使用 chrome.storage.local更新该对象。在回调中设置



如果多次出现竞争条件,则执行回调。我能做些什么来避免这种情况?



我知道它可以通过 jQuery.defer 来解决,但是在那里任何方法来做一个原子更新?或者有什么建议来改进我的代码?



下面是一个非常简单的例子:

  chrome.tabs。 onCreated.addListener(function(tab){//同时有很多
//测试
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同步。



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


I get an object from chrome.storage.local.get and then I want to update that object by using chrome.storage.local.set in the callback.

If the callback is executed multiple times a race condition happens. What can I do to avoid this?

I know it can be resolved by jQuery.defer, but is there any method to do an atomic update? Or any suggestions to improve my code?

Below is a very simple example:

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

解决方案

One solution is to use localStorage in combination with chrome.storage.

You can use localStorage for all the frequent get and set from your listener. Setting and getting localStorage is synchronous/blocking so there is no need to worry about race conditions.

You can then decide some idle time/event to sync localStorage with chrome.storage.

This would work assuming that the user will be using this extension at one computer at any one time.

这篇关于铬扩展chrome.storage如何做很多获取和设置相同的时间,并避免竞争状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆