-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetchWithReTry.js
More file actions
40 lines (35 loc) · 1.12 KB
/
fetchWithReTry.js
File metadata and controls
40 lines (35 loc) · 1.12 KB
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
32
33
34
35
36
37
38
39
40
const fetchWithRetry = async (url, options = {}, retryOptions = {}) => {
const {maxRetries = 3, delay = 1000} = retryOptions
// 当前记录次数
let nowCounts = 0
while (nowCounts <= maxRetries) {
try {
const response = await fetch(url, options)
if (response.ok) {
return response
}
if (response.status === 500) {
if (nowCounts <= maxRetries) {
// 暂停2秒
await new Promise((resolve, reject) => setTimeout(() => resolve, delay))
nowCounts++
} else {
throw new Error('达到最大重试次数')
}
} else {
throw new Error('出现其他请求错误')
}
} catch (error) {
console.warn('请求因为其他异常失败了')
await new Promise(resolve => setTimeout(resolve, delay));
nowCounts++
}
}
}
async function testMyUrl() {
const data = await fetchWithRetry('', {
body: {}
}).json()
return data
}
testMyUrl()