Resolving Promises with EventListener

I am working on a popup div, and I would like to get a promise attached to the animation so that I can do something after the popup has ended.

My approach does not work because I could not find a way to pass the promise of the function to the event handler. It seems you cannot use bind here. I tried, and although I can resolve the promise, I cannot remove the event handler

What will be the other solution here?

function EventListenerForPopUp() { this.removeEventListener("animationend", EventListenerForPopUp ); this.Show.resolve(); } function ShowHideDiv() { this.Show = function () { return new Promise(function(resolve, reject) { this.Div.addEventListener("animationend", EventListenerForPopUp, false); }.bind(this)); } } 
+8
source share
2 answers

You do not need to pass the promise to the event handler, you need to pass the resolve callback:

 function EventListenerForPopUp(resolve) { this.removeEventListener("animationend", EventListenerForPopUp ); resolve(); } // [...] return new Promise(function(resolve, reject) { this.Div.addEventListener("animationend", function() { EventListenerForPopUp.call(this, resolve); }, false); 

It looks a little ugly to me, maybe you can look at something like this:

 var div = this.Div; return new Promise(function (resolve) { div.addEventListener("animationend", function animationendListener() { div.removeEventListener("animationend", animationendListener); //call any handler you want here, if needed resolve(); }); }); 
+14
source

Alternatively, we can create a reusable utility function as a means of creating a promise from any DOM event:

 const createPromiseFromDomEvent = (eventTarget, eventName, run?) => new Promise(resolve => { const handleEvent = () => { eventTarget.removeEventListener(eventName, handleEvent); resolve(); }; eventTarget.addEventListener(eventName, handleEvent); if (run) run(); }); 

Usage example (with source MSE buffer):

 await createPromiseFromDomEvent( sourceBuffer, 'updatend', () => sourceBuffer.remove(3, 10) ); 

Depending on the situation, the run parameter may be required to provide user code that starts the asynchronous operation (as described above), or it may be skipped if we know that the operation has already begun.

0
source

Source: https://habr.com/ru/post/1244193/


All Articles