I searched a lot but found nothing about it, just this question.
And I wanted something asynchronous without relying on loops to check, so I did a different solution.
The main problem was solving a promisse with an event listener, so I made the eventListener function inside the promisse and I use an arrow function to get the context of the promisse. Then I resolve the promise and cancel the eventListener after the first click.
And to make a function reusable with any listener I put an entry for that too.
function waitListener(element, listenerName) {
return new Promise(function (resolve, reject) {
var listener = event => {
element.removeEventListener(listenerName, listener);
resolve(event);
};
element.addEventListener(listenerName, listener);
});
}
It will return the event if you want to use it for something.
This makes it easier for you to write some sequence of codes in an orderly way. But to work it has to be inside an asynchronous function, which means that this function will start to run in parallel, so it is important to know where you are going to start in order not to hinder your process.
A simple use within some asynchronous function:
var element = document.querySelector("button");
await waitListener(element,"click");
A full sample:
function waitListener(Element, ListenerName) {
return new Promise(function (resolve, reject) {
var listener = event => {
Element.removeEventListener(ListenerName, listener);
resolve(event);
};
Element.addEventListener(ListenerName, listener);
});
}
async function awaitClicks(){
var element = document.querySelector("button");
await waitListener(element,"click")
// Do thing 1
.then(e=>{
console.log("e.clientX: "+e.clientX);
});
console.log(1);
await waitListener(element,"click");
// Do thing 2
console.log(2);
await waitListener(element,"click");
// Do thing 3
console.log(3);
}
awaitClicks();
<button>click</button>
If you need the same thing to happen every time you click a button, it is preferable to use just one addEventListener. And depending on what you are going to do you can use an addEventListener and cancel it already in the function it does using the removeEventListener. Now if you want to do something that depends on an order of events, maybe using this function can be a good solution.
once
instead ofon
, as the promise can resolve only once and it should automatically remove the handler after that. – Beevesvar input =
happens? Wondering if i need to put await on each of those too – Gyrfalcon