Orry
Orry

Reputation: 659

Resolve javascript promise on DOM event

I've been looking for an answer but couldn't find none for my issue (or at least I didn't understand how to make it work for mine.) So I have this function:

Test.prototype.testing = function(){
  return new Promise(function (resolve, reject){
    document.getElementById("element").innerHTML = 
      "<button onclick=\"\">Next</button>";
  });
};

How can I make the promise resolve on button click? Thanks in advance.

Upvotes: 1

Views: 1602

Answers (3)

Ben Aston
Ben Aston

Reputation: 55729

Something like this?

function Test() {}

Test.prototype.testing = function(){
  return new Promise(function (resolve, reject){
    const btn = document.createElement("button")
    btn.innerHTML = 'Next'
    btn.addEventListener('click', resolve);
    document.getElementById("element").appendChild(btn)
  });
};

(new Test()).testing()
<div id="element"></div>

Upvotes: 1

David784
David784

Reputation: 7464

A better way would be to already have the button in the DOM, and then reference it. At that point it's a simple matter of setting the onclick event handler to the resolve function. (You could also use addEventListener if you want)

var elBtn = document.getElementById('resolver');
function Test(){ }

Test.prototype.testing = function(){
  return new Promise(function (resolve, reject){
    elBtn.onclick = resolve;
  });
};

var t = new Test();
t.testing().then(x=> {
  console.log('resolved!');
});
<button id='resolver'>Click me!</button>

Upvotes: 0

Leandro Matilla
Leandro Matilla

Reputation: 1011

You can do it. By using the CustomEvent API for the browser environment.

function myPromiseReturningFunction() {
  return new Promise(resolve => {
    window.addEventListener("myCustomEvent", (event) => {
       resolve(event.detail);
    }) 
  })
}

myPromiseReturningFunction().then(result => {
   alert(result)
})

document.getElementById("element").addEventListener("click", () => {
   window.dispatchEvent(new CustomEvent("myCustomEvent", {detail : "It works!"}))
})
<p id="element"> Next </p>

Upvotes: 1

Related Questions