0

我在 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 = falsewhich 在 while 循环中永远不会成立。

如果有人知道为什么它在 while 循环中没有设置为 true,请告诉我。

4

1 回答 1

3

从 sync.get 返回的 obj 是 {userName: value} - 使用 obj.userName。

isCurrentValueSet 未设置为 true 的原因是该函数是异步的 - 当回调执行时,它无权访问类变量 isCurrentValueSet。

你想要达到的目标是错误的。事实上,为了用户和浏览器的性能,存储请求是异步的。你必须学会​​围绕它进行设计,当你习惯它时它就很容易了。

您可以一次检索多个变量,因此如果您有一段代码需要多个变量,只需执行以下操作:

chrome.storage.sync.get({a:"",b:"",c:0,d:[]}, function(result) {
  a = result.a
  b = result.b
  c = result.c
  d = result.d
  your code
});

通过传入一个对象,您可以请求多个变量为它们在存储中不存在时定义默认值。当然,您不必提取变量。

于 2017-11-05T21:20:36.967 回答