I want to create a listener function to listen changes of global variable. The use case is, when I made a ajax call, i flag isAjaxDone variable to false, once its done then flag it to true. So the listener will process something once detected the isAjaxDone is true.
i tried asyc ... await & Promise but i still can't achieve what i want. The entire method still run asynchronously outside, except the method inside asyc ... await & Promise.
Here is what i have tried:
var isAjaxDone = null
var timeout = 0
function listener(){
let waiter = function(){
return new Promise(resolve=>{
setTimeout(() => {
timeout += 1
listener()
}, 100);
})
}
if(isAjaxDone) return true
if(isAjaxDone === null) return false
if(isAjaxDone === false){
if(timeout < 300){
return waiter()
}
else{
return "timeout"
}
}
}
Implementation:
function checker(){
var ajaxStatus = listner()
if(ajaxStatus){
//...
}
}
When i call isAjaxDone, it will return me a Promise function instead of boolean.
I prefer not to use Promise...then because the function i wrote is consider as library, I don't want the user wrap a bunch of code inside the then because it will caused some problem to user code structure. Same goes to the Callback.
I would like to let it wait until either return timeout or boolean only, please advise.
isAjaxDone = truewhen the AJAX completes, just do your processing there instead.resolves at the end of xhr.onload.then(data=>{ //...})and i prefer "status/variable dependency" more than "function dependency", so user just have to check status instead of run the callback.listener()return boolean only.