Search code examples
javascriptasynchronousasync-awaitaddeventlistener

How can I await an event listener inside a function?


I'm trying to wait for a button to be clicked before proceeding inside another function.

async function foo() {
    // code before
    await ??? // wait for start button to be clicked before proceeding
    // code after
}

startButton.addEventListener("click", function() {
    return new Promise(); // ???
}, false);

How can I use an event listener inside another function?


Solution

  • You're on the right track with returning a new Promise(). You can do something along these lines:

    async function btnClick(btn) {
      return new Promise(resolve =>  btn.onclick = () => resolve());
    }
    

    then in your calling code:

    await btnClick(startButton);