我在 JavaScript 文件中创建了一个本地类,其内容如下:
class CustomChromeStorage {
//#region userName
get userName() {
let isCurrentValueSet = false;
chrome.storage.sync.get('userName', function (obj) {
this._userName = obj;
isCurrentValueSet = true;
});
while (true) {
if (isCurrentValueSet) {
return this._userName;
}
}
}
set userName(newValue) {
this._userName = newValue;
chrome.storage.sync.set({ 'userName': newValue }, function () {
});
}
remove_userName() {
this._userName = null;
chrome.storage.sync.remove('userName', function () {
});
}
//#endregion userName
我做这种类型代码的想法是当我在我的代码中的其他地方编写时,例如:
alert(new CustomChromeStorage().userName);
然后我的代码只是从 chrome 存储中获取用户名并通过警报显示它。为了从 chrome 存储中获取一个值,我们需要提供一个回调作为参数值。我知道这是异步过程的好习惯,但有时处理所有回调对我来说变得很麻烦。
当我通过自定义类从 chrome 存储中获取值以异步执行当前代码时,我希望这样做。这就是为什么我在该属性的 getter 方法中编写了无限 while 循环,但问题是当我尝试通过自定义 chrome 存储类提醒用户名时,我的整个程序执行会挂起。
其背后的原因是我最初设置isCurrentValueSet = false
which 在 while 循环中永远不会成立。
如果有人知道为什么它在 while 循环中没有设置为 true,请告诉我。