Home > database >  Changing a declared var inside a function
Changing a declared var inside a function

Time:06-05

I need help with my script. Basicly my problem is that i have a variable declared with null, then inside a function changed to some value and then returned. But when i return it it still returns as null, not the thing i set it to. Anyone here to help?

Script:

var grade=""
var gradeStyle=""
var finalColor=""
function getSettings(){
    chrome.storage.sync.get("grade",function(res){
        grade=res.grade
    })
    chrome.storage.sync.get("gradeStyle",function(res){
        gradeStyle=res.gradeStyle
    })
    chrome.storage.sync.get("finalColor",function(res){
        finalColor=res.finalColor
    })
    return [grade,gradeStyle,finalColor]
}
export {getSettings};

CodePudding user response:

EDIT:

var response;
function getSettings(){
    chrome.storage.sync.get(["grade","gradeStyle","finalColor"],function(res){
    response=res;
    });
    return res;
}
export {getSettings};

CodePudding user response:

The values are null because you are assigning these variables inside a callback function before returning them. It means that, the return values will not be assigned to variables until the promises completely resolves. To solve that, you can use the async-await syntax.

async function getSettings(){
    const grade = await chrome.storage.sync.get("grade").promise();
    const gradeStyle = await chrome.storage.sync.get("gradeStyle").promise();
    const finalColor = await chrome.storage.sync.get("finalColor").promise();
    return [grade,gradeStyle,finalColor]
}
export {getSettings};

Note that, to use the getSettings function now, you have to call it inside another async function, and you should await for its returning results.

  • Related