Hello I'm trying to call the function "tryToGetData" using a recursive function inside a promise so it can pass me another different random value in order to keep trying to get a "success" response, at least, until the counter is set to 5 and if not just print 'Unable to load HTML'.
But the thing is that once I get the randomvalue it looks like no matter how many times I call the function to retrieve another random value it'll always be the same value as you can see below.
First, this is my code:
var a = ['unsuccessful', 'success'];
var randomValue = a[Math.floor(a.length * Math.random())];
let statuscounter= 0;
Promise.resolve(randomValue)
.then((value) => {
console.log(value)
return value
})
.then(function tryToGetData(status) {
if (status !== "success" && statuscounter <= 5) {
console.log('First attempt');
statuscounter +=1
return tryToGetData(randomValue)
} else if(status !== "success" && statuscounter > 5){
console.log('Unable to load HTML');
return false;
}else{
console.log('HTML loaded, wait to load resources');
}
})
.catch(error => reject(err));
This is the output if I get unsuccessful as the random value:
"unsuccessful"
"First attempt"
"First attempt"
"First attempt"
"First attempt"
"First attempt"
"First attempt"
"Unable to load HTML"
Whereas what I want is for example this:
"unsuccessful"
"First attempt"
//call the function again and in that case I'll get "success" as randomvalue:
"success"
"HTML loaded, wait to load resources"