Chrome.storage.sync.get不在本地变量中存储值 [英] Chrome.storage.sync.get not storing value in local variable

查看:100
本文介绍了Chrome.storage.sync.get不在本地变量中存储值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function getBugVal() {
    var bugVal = "";

    chrome.storage.sync.get('bugId', function (obj) {
        console.log(obj.bugId);
        bugVal = obj.bugId;
        console.log(bugVal + "<- val inside get sync");
    });

    console.log(bugVal + "<- val outside get sync");
    return bugVal;
}

如果我调用getBugVal(),则返回值将始终指示空字符串,而不是chrome.storage.sync.get中的实际值.bugVal甚至没有保存字符串值.

If I call getBugVal() the return value keeps indicating an empty string instead of the actual value from the chrome.storage.sync.get. bugVal is not even saving the string value.

console.log(bugVal + "<- val inside get sync");

在内部函数调用中产生正确的值.有想法吗?

yields the correct value within the inner function call. Thoughts?

推荐答案

是的.这就是异步代码的工作方式.您将必须使用回调.这样的事情可能会起作用.

Yep. That's how async code works. You'll have to use callbacks. Something like this would probably work.

function workWithBugVal(val) {
    // Do stuff
}

function getBugVal(callback) {
    var bugVal = "";

    chrome.storage.sync.get('bugId', function (obj) {
        console.log(obj.bugId);
        bugVal = obj.bugId;
        callback(bugVal);
    });
}

getBugVal(workWithBugVal);

这篇关于Chrome.storage.sync.get不在本地变量中存储值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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