1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| function withTimeout(promise, timeoutMs, timeoutMessage = "操作超时") { const timeout = new Promise((_, reject) => { setTimeout(() => reject(new Error(timeoutMessage)), timeoutMs); }); return Promise.race([promise, timeout]); }
function retry(fn, retries = 3, delay = 1000) { return new Promise((resolve, reject) => { const attempt = (attemptsLeft) => { fn() .then(resolve) .catch((error) => { if (attemptsLeft <= 0) { reject(error); } else { console.log(`重试剩余 ${attemptsLeft} 次`); setTimeout(() => attempt(attemptsLeft - 1), delay); } }); }; attempt(retries); }); }
retry(() => withTimeout(fetch("/api"), 5000), 3) .then((response) => console.log("成功")) .catch((error) => console.log("最终失败:", error));
|