使用 chrome.storage.sync 时未按正确的顺序遍历树



我正在尝试对树结构执行DFS遍历,存储为映射Root_Node_Value -> Array_of_Children。当我尝试执行遍历时,将映射存储为普通对象,树将按预期遍历。

// Correct DFS 
treeMapping = {'1221':['1223','1224']}
function closeTree(root) {
const children = treeMapping[root] || [];
children.forEach(function (child) { closeTree(child) });
console.log("Closing: "+root);
}

正如预期的那样,上述代码的输出为:1223, 1224, 1221

但是,当我尝试实现相同的逻辑时,使用chrome.storage.sync检索映射,没有遵循预期的顺序。

// Incorrect DFS
function closeTree(root) {
chrome.storage.sync.get(root.toString(), data => {
const children = data[root] || [];
children.forEach(function(child) { closeTree(child); });
console.log("Closing: "+root);
});
}

使用chrome.storage.sync的代码输出1221, 1222, 1226,即使存储在存储中的树映射是相同的。这显然是不正确的,因为根值1221应最后打印。

// Retrieved value using chrome.storage.get('1221', ...)
{1221: Array(2)}
1221: (2) [1222, 1226]

此行为的原因是什么,我该如何解决?

chromeAPI 是异步的。一个简单的经验法则是,如果该方法接受每个文档的回调,则它会异步运行。

最简单的解决方案是propromise closeTree 并在孩子身上使用 Promise.all:

function closeTree(root) {
return new Promise(resolve => {
chrome.storage.sync.get(root.toString(), async data => {
const children = data[root] || [];
await Promise.all(children.map(closeTree));
resolve();
});
});
}

附言您可以通过在一次操作中读取所有子项来显着优化:
chrome.storage.sync.get(children, processAllChildren)

最新更新