// Promise.retry 超时重新请求,并在重试一定次数依然失败时输出缓存内容
async function retry(url, times,res = []){
if(times===0){
console.log(res)
return Promise.reject("failed")
}
let ans = null
try {
const ans = await Promise.race([myFetch(url), new Promise((resolve, reject)=>{
setTimeout(()=>{
reject("reason")
},1000)
})])
// 如果await Promise.race出错了,直接跳到catch里面
// console.log(a)
}catch (e) {
res.push(e)
// console.log(e)
}finally {
console.log("try finish")
if(ans!==null){
//没出错,但是可能之前出错了..这次没出错,所以应该改为
return Promise.resolve("success")
}else{
retry(url, times-1,res)
}
}
}
function myFetch(url){
return new Promise((resolve, reject)=>{
setTimeout(()=>{
resolve("success")
},1100)
})
}
(async function() {
try{
await retry("test", 2)
}catch(e){
console.log(e)
}
// console.log(await retry("test", 2))
})()
console