Home > Software design >  how to wait for user to click then console log variable
how to wait for user to click then console log variable

Time:05-10

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?

CodePudding user response:

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>

CodePudding user response:

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.

CodePudding user response:

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

  • Related