function promiseRetry(fn,retries = 3,delay = 1000) {
return new Promise((resolve,reject)=>{
function attempt(remainingRetries) {
fn()
.then(resolve)
.catch((err) =>{
if(remainingRetries<=0) {
reject(err)
} else {
setTimeout(()=> {
attempt(remainingRetries -1)
}, delay)
}
})
}
attempt(retries)
})
}
let count = 0;
function unreliableTask() {
return new Promise((resolve,reject)=>{
count++;
console.log(`尝试第${count}次`);
Math.random() > 0.5 ? resolve("成功") : reject("失败")
})
}
promiseRetry(unreliableTask,5, 500).then(console.log)
.catch(console.error)
console