I am working on a popup div and I would like to have a promise attached to the animation so I can do something after the popup ended.
My approach does not work because I could not find a way to pass the promise to the function on the event handler. Seems you cannot use bind here. I have tried and although I can resolve the promise, I cannot remove the event handler
What would be a different 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));
}
}
The Promise. resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.
Resolving a promise to another promise will automatically make it wait for the other promise's result. This is what makes promises chainable (returning further promises in then() callbacks).
A resolved promise means, that the code handled by the promise is done, and the code in the callback passed to the then method is executed with the resolved value passed in.
We must always add a catch() , otherwise promises will silently fail. In this case, if thePromise is rejected, the execution jumps directly to the catch() method. You can add the catch() method in the middle of two then() methods, but you will not be able to break the chain when something bad happens.
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);
This looks a bit 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();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With