Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading