promise超时重传
1. 设置一个promise函数 用settimeout控制重传的过程
2. 设置一个promise 函数 用try’包裹 执行fun 成功直接输出 失败catch 一次失败 没有times就全失败 catch这个错误
function fun() {//封装请求执行的过程 用演示器所以用promise
let n = Math.random();
return new Promise((resolve, reject) => {
setTimeout(() => {
if (n > 0.7) {
resolve(n)
} else reject(n);
})
}, 500)
}
//封装发送请求
function retry(fun, times) {
new Promise(async (resolve, reject) => {
while (times--) {
try {
const res = await fun();//成功就接着执行下面的
resolve(res)//把这个promise的结果值为成功
console.log('成功', res);
break;
} catch (error) {//error为fun reject的结果
console.log('失败一次',error);
if (!times) {
reject(error)
}
}
}
}).catch(()=>{
console.log('全部失败');
}
)
}
retry(fun,3)