我正在开发一个 Chrome 扩展,我将存储服务器发送的对象。 例如,我会收到:
命令= {id:“1”,类型:“A”,大小:“B”,优先级:“C”}
如果我有一个数据库,我会将其作为一行插入表中
commands
。
使用 chrome.storage,我将这些对象的数组存储在键 commands
中。
但是,当我通过服务器收到新命令时,我必须从本地存储中获取,更新数组,然后再次设置。我担心在获取和设置或删除存储的命令时收到另一个命令的情况。我正在考虑信号量,但我不知道这是否是一个好主意。
有人可以建议我该怎么做吗?
谢谢!
扩展可以使用数据库:IndexedDB(示例代码可能看起来很复杂,但在实际扩展中非常简单,例如两个小函数here,getStyles和saveStyle,或IDB-keyval包装库)。
如果你想使用
chrome.storage
,只需维护一个全局queue
数组
const queue = [];
由服务器侦听器填充:
queue.push(newItem);
updateStorage();
updateStorage 也可能是一个全局函数:
function updateStorage() {
if (!queue.length || updateStorage.running) {
return;
}
updateStorage.running = true;
chrome.storage.local.get('commands', data => {
data.commands = [].concat(data.commands || [], queue);
queue = [];
chrome.storage.local.set(data, () => {
updateStorage.running = false;
if (queue.length) updateStorage();
});
});
}