I have this promise:
function getAPI(token)
{
return new Promise((resolve, reject) => {
console.log("Request 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 + " - Calling Myself in 5 Seconds");
setTimeout(function(){
getAPI(token);
},5000);
}
else{
console.log('Call API - Giving Result');
resolve(response.responseText.split("_")[1]);
}
}
});
});
}
I call it inside of itself when the answer is not what I want, cannot be less than 5 seconds though.
Then I do this in the main function:
setTimeout( function(){
getAPI(token).then((key) => {
console.log(key);
doSomethingWithKey;
setTimeout( function(){
loop();
},1000);
}).catch(() => {
console.log('Error na api - reload page!');
location.reload();
});
},25000);
But I noticed that when getAPI calls itself cause answer is not what i want, the '.then' in the main function never executes and my code hangs there. How can I fix it? I don't understand much of promises but I can't see why it hangs ...