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?
>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>