Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
Changing a declared var inside a function

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};
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

EDIT:

var response;
function getSettings(){
    chrome.storage.sync.get(["grade","gradeStyle","finalColor"],function(res){
    response=res;
    });
    return res;
}
export {getSettings};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda