参考答案:
下面是一个简单的示例实现,并未包含对异常情况的处理、超时设置等较复杂的功能:
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