It seems like an odd design, but as Bergi comments, there's nothing stopping you from doing it -
function my_func () {
return new Promise(r =>
document.forms.myapp.mybutton.onclick = r
)
}
function main () {
my_func().then(event => console.log(event.target))
}
main()
<form id="myapp">
<button type="button" name="mybutton">Click me</button>
</form>
A Promise can be resolved a maximum of one time, so it probably makes sense to automatically remove the event listener after the first click. We could rename my_func
to onclick
and give it a parameter to make it reusable -
function onclick(elem) {
return new Promise(r =>
elem.addEventListener("click", r, {once: true})
)
}
function main () {
onclick(document.forms.myapp.mybutton)
.then(event => console.log(event.target))
onclick(document.forms.myapp.otherbutton)
.then(event => console.log(event.target))
}
main()
<form id="myapp">
<button type="button" name="mybutton">A</button>
<button type="button" name="otherbutton">B</button>
</form>
Now onclick
can be used in more interesting ways. For example, we could make a button that needs two clicks before the effect is triggered -
function onclick(elem) {
return new Promise(r =>
elem.addEventListener("click", r, {once: true})
)
}
function main () {
onclick(document.forms.myapp.mybutton)
.then(event => console.log(event.target))
onclick(document.forms.myapp.otherbutton)
.then(_ =>
onclick(document.forms.myapp.otherbutton)
.then(event => console.log(event.target))
)
}
main()
<form id="myapp">
<button type="button" name="mybutton">click once</button>
<button type="button" name="otherbutton">click twice</button>
</form>