Skip to content

Instantly share code, notes, and snippets.

@agileago
Created May 12, 2022 13:55
Show Gist options
  • Save agileago/b96cb1e5c52a66f75b093c8dd3ffd337 to your computer and use it in GitHub Desktop.
Save agileago/b96cb1e5c52a66f75b093c8dd3ffd337 to your computer and use it in GitHub Desktop.
超时重试
interface ResponseData {
code: -1 | 0 | 1
msg: string
data: any
}
function getData(timeout: number) {
return Promise.race([
new Promise<ResponseData>((resolve, reject) => {
setTimeout(() => {
const random = Math.random()
if (random > 0.5) {
resolve({ code: 0, msg: '', data: 'success' })
} else if (random > 0.1 && random < 0.4) {
resolve({ code: 1, msg: '', data: 'success' })
} else {
resolve({ code: -1, msg: '', data: '-1' })
}
}, Math.random() * 4000)
}),
new Promise<ResponseData>((resolve, reject) => setTimeout(reject, timeout, new Error('timeout')))
])
}
const EXCEPTION = Symbol('exception')
async function request() {
let i = 1
let isRetry = false
while (i > 0) {
let res = await getData(3000).catch(e => EXCEPTION)
if (typeof res === 'symbol') {
if (isRetry) {
i--
} else {
isRetry = true
i = 5
}
} else {
if (res.code === -1) throw new Error('获取数据失败,请稍后重试')
else return res.data
}
}
throw new Error('获取数据失败,请稍后重试')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment