Promise失败后重试
function fn() {
const n = Math.random();
return new Promise((resolve, reject) => {
setTimeout(() => {
if (n > 0.7) {
resolve(n)
} else {
reject(n)
}
}, 1000);
})
}
Promise.retry = (fn, times) => {
new Promise(async (resolve, reject) => {
while (times--) {
try {
const res = await fn()
console.log("success", res);
resolve(res);
break;
} catch (error) {
console.log('fail', error);
if (!times) {
reject(error)
}
}
}
}).catch((err) => {
console.log("重试也失败了");
})
}
Promise.retry(fn, 3)