你好我试图调用函数" tryToGetData"在promise中使用递归函数,这样它就可以传递给我另一个不同的随机值,以便继续尝试获得成功"至少响应,直到计数器设置为5,如果不打印,则无法加载HTML'。
但问题是,一旦我得到随机值,看起来无论我多少次调用该函数来检索另一个随机值,它总是与您在下面看到的值相同。
首先,这是我的代码:
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));
&#13;
如果我作为随机值不成功,这是输出:
"unsuccessful"
"First attempt"
"First attempt"
"First attempt"
"First attempt"
"First attempt"
"First attempt"
"Unable to load HTML"
虽然我想要的是例如:
"unsuccessful"
"First attempt"
//call the function again and in that case I'll get "success" as randomvalue:
"success"
"HTML loaded, wait to load resources"