Mine is a simple button which make a xmlRequest Call to a json file in local server. its doing fine. but now i want to return a promise from inside the function
const button = document.getElementsByClassName('button')[2]
button.addEventListener('click', getJson)
function getJson() {
this.xhr = new XMLHttpRequest()
this.xhr.open("GET", "jsondata.json", true)
this.xhr.onload = () => {
return new Promise(
(resolve, reject) => {
console.log(this.xhr.responseText)
resolve('this is success')
}
)
}
this.xhr.send()
}
but where do i catch the resolve and reject that the function getJson returns....I have tried passing the callback to the add event listener like
button.addEventListener('click', getJson(callback))
function callback(result) {
console.log(result)
}
but the callback executes right away when the dom loads...i know its because of the parenthesis () i gave to getJson in the addEventListener...but i am falling in the same loop...so is there any way to add then functionality to the addEventListener because i want to get the Promise in return