需求情況比較簡(jiǎn)單: 需要在前端實(shí)現(xiàn)一個(gè)重試的功能粹污,如果一個(gè)請(qǐng)求訪問出錯(cuò)(不管是后端服務(wù)出錯(cuò)還是網(wǎng)絡(luò)出錯(cuò),亦或者是請(qǐng)求的結(jié)果不符合預(yù)期)均可進(jìn)行自動(dòng)重試
直接上代碼
<!DOCTYPE html>
<html>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
//最大重試次數(shù)
const MAX_RETRY = 3
//請(qǐng)求超時(shí)時(shí)間
const REQUEST_TIMEOUT = 15 * 1000
// 重試間隔500ms
const RETRY_INTERVAL = 500
function sleep(ms){
return new Promise((resolve)=>setTimeout(resolve,ms));
}
async function request(url,method,params,retry = MAX_RETRY,hookResult = null){
let res
let requireRetry
try {
//構(gòu)造請(qǐng)求的參數(shù)
let config = {
url: url,
method: method,
timeout: REQUEST_TIMEOUT
}
if(Object.is(method,'get')){
config['params'] = params
}else if (Object.is(method,"post")){
config['data'] = params
}
res = await axios.request(config)
//發(fā)生服務(wù)器錯(cuò)誤,重試
if (res && res.status > 500){
console.log('返回的狀態(tài)碼:', res.status)
requiretRetry = true
}
//使用調(diào)用者邏輯判斷馅而,如果未達(dá)到期許,重試
if (hookResult && !hookResult(res)){
console.log('hookResult函數(shù)返回為false,需要重試')
requiretRetry = true
}
}catch(err){
console.log(err)
// 發(fā)生網(wǎng)絡(luò)錯(cuò)誤宴倍,重試
requireRetry = true
}
if (requireRetry && retry > 0){
// 500ms之后重試
await sleep(RETRY_INTERVAL)
console.log('重試', retry)
res = await request(url, method, params, --retry, hookResult)
}
return res
}
//use example
async function test()
{
let res =await request("https://www.baidu.com/s","get",{"wd":"hello"})
console.log("result is : " , res)
}
</script>
<body >
<button type="button" onclick="test()">Click Me!</button>
</body>
</html>