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

155
Visualizações
how to wait for user to click then console log variable

So right now I am having some trouble with the async/await functions and my goal is to update a variable when the user clicks a button. After this is done then I console log the updated variable. For example in my code I create a global variable called result and then I have a function with an event listener to change the value of the variable when the button is clicked but when I console log the variable I get an undefined variable and not the value I set it to. Here is the code: JS file

let onlyBtn = document.getElementById("onlyButton");


let result;

async function realMain(){

   await step();
   console.log(result);

}

async function step(){
    return new Promise((resolve) =>{
        onlyBtn.addEventListener("click", function(){
            result = "nice";
            
        });
        resolve();
    });
    
        
}

realMain();

HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>

    <div>
        <button id="onlyButton">Run</button>
    </div>
    


    <script src="app.js">
        
    </script>

    
</body>
</html>

How can I make it so I have to wait for the function where the update is done, then I console log the updated variable?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

When you console.log in realMain function. The result variable is still not set. The value is set when onlyBtn receives click event. So you just need to print the result in the event callback.

And assuming your snippet is your full code, the logic for step async function is wrong. It is not doing anything related to async, just setting up an event listener. So it should not be async at all.

about 4 years ago · Juan Pablo Isaza Relatório

0

your code is not triggering event by clicking, and you should pass argument result in resolve

let onlyBtn = document.getElementById("onlyButton");

let result;

async function realMain() {
    await step().then((res) => {
        console.log(res);
    });
}

async function step() {
    return new Promise((resolve) => {
        onlyBtn.addEventListener("click", function () {
            result = "nice";
            resolve(result);
        });
    });
}

realMain();
<div>
    <button id="onlyButton">Run</button>
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

You juste need to move you resolve() call into you eventListener, look here

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