Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

resolving a promise with EventListener

Tags:

javascript

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));
    }
}
like image 962
Jose Neto Avatar asked Mar 01 '16 09:03

Jose Neto


People also ask

How do I resolve promise results?

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.

Can you resolve a promise with a promise?

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).

What does resolving a promise mean?

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.

How do you handle promise rejection?

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.


1 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);

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();
    });
});
like image 79
Volune Avatar answered Oct 26 '22 04:10

Volune