简体   繁体   中英

How to use async/await on event handlers on buttons in JavaScript?

I'm new too JavaScript and am having trouble with async. I have a webpage with two buttons, If the yes button is pressed it will do some code and if the no button is pressed it will do different code but regardless of which one is pressed it will continue on in the function. For Example

function mainloop(){

        document.getElementById("buttonyes").addEventListener("click", () => {
            /* do some code */
        })
        
        document.getElementById("buttonno").addEventListener("click", () => {
            /* do some different code */
        })
        /* wait for either button to be pressed and then continue with code */
        console.log("yay waiting for stuff")
}

I believe the solution to this is promises and creating other functions to handle the buttons; however, tutorials I've seen only show one function solutions and if I understand correctly the EventListener when activated is using another function all to itself. I've come over from C and all this object properties asynchronization stuff is throwing me for a loop.

I'd really love a way to keep it all in the same main function as this challenge specifically called for me to use async/await on this damned buttons.

An Event Handler is already a way of using asynchronous code. The code inside the handler already waits to be executed until somebody presses the button.

If you have some function that needs to be executed after both clicks you can simply add it to both event handlers. Btw you don't need to put the addEventListener in a loop. Just add them once.

    document.getElementById("buttonyes").addEventListener("click", () => {
        /* do some code */
      
        myNewFunction()
    })
    
    document.getElementById("buttonno").addEventListener("click", () => {
        /* do some different code */

        myNewFunction()
    })


    /* wait for either button to be pressed and then continue with code */
    function myNewFunction() {
         console.log("yay waiting for stuff")
    }

You only need another async await if the code in the buttons does something that needs to be awaited, for example fetching data from the internet. Or else we need a bit more context to know why you want to solve this problem with an extra async await .

I would advise you to use the async await with promise to handle this kind of scenario. eventHandler supports the async await under the hood.

Please check this example:-

document.querySelector('#btn')
  .addEventListener('click', handleClick)

async function handleClick() {
  await new Promise((resolve) =>
                    setTimeout(resolve, 5000))
  alert('clicked')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM