I have come across this interesting challenge:
function getAPI(token)
{
return new Promise((resolve, reject) => {
console.log("Requesting API");
GM_xmlhttpRequest({
method: "GET",
url: "URL"+token,
onload: function(response) {
console.log(response.responseText);
if( response.responseText == "NOT_ANSWER" || response.responseText.indexOf("ERRO") > -1 ){
console.log(response.responseText + " - Recursive call in 5 Seconds");
setTimeout(function(){
getAPI(token);
},5000);
}
else{
console.log('Call API - Result obtained');
resolve(response.responseText.split("_")[1]);
}
}
});
});
}
I find it intriguing how I call the function within itself when the answer is not as expected, always waiting at least 5 seconds.
This leads me to the main function where I execute:
setTimeout( function(){
getAPI(token).then((key) => {
console.log(key);
doSomethingWithKey;
setTimeout( function(){
loop();
},1000);
}).catch(() => {
console.log('Error in API - reloading page!');
location.reload();
});
},25000);
However, I have noticed a strange behavior. When getAPI calls itself due to unexpected answers, the '.then' block in the main function does not seem to run, causing my code to hang indefinitely. How can I address this issue? I am still learning about promises and struggling to understand why this happens...