问答题1161/1587实现一个请求函数:fetchWithRetry,要求会最多自动重试 3 次,任意一次成功就直接返回

难度:
2023-05-30 创建

参考答案:

下面是一个简单的示例实现,并未包含对异常情况的处理、超时设置等较复杂的功能:

1function fetchWithRetry(url, options, maxRetry = 3) { 2 return new Promise((resolve, reject) => { 3 const doFetch = async (attempt) => { 4 try { 5 const response = await fetch(url, options); 6 if (response.ok) { 7 resolve(response); 8 } else { 9 throw new Error('Request failed'); 10 } 11 } catch (error) { 12 if (attempt < maxRetry) { 13 console.log(`Attempt ${attempt + 1} failed. Retrying...`); 14 doFetch(attempt + 1); 15 } else { 16 reject(new Error('Max retries exceeded')); 17 } 18 } 19 }; 20 21 doFetch(0); 22 }); 23}

最近更新时间:2023-07-08

赞赏支持

预览

题库维护不易,您的支持就是我们最大的动力!