在你请求接口的过程中,可能这个接口返回的状态是随机的,如果是失败的状态你需要让他重新再次去进行请求,并且限制它的重复请求次数
使用 Promise 简单做一个封装,接受一个 promise 方法和一个 最大重复请求次数
// 成功和失败概率都为 50%
const randomErrorFunction = () => new Promise((resolve, reject) => Math.random() < 0.5
? resolve('SUCCESS') : reject('ERROR'))
const errorFunction = (promiseFun, time) => {
let overtime = 0;
// 此处判断是否返回失败状态,重新执行
const deepCatch = () => {
return promiseFun().catch((error) => {
if (overtime < time) {
overtime++
return deepCatch()
}
return error
})
}
return deepCatch()
}
const test = errorFunction(randomErrorFunction, 5)
test.then(response => response === 'SUCCESS' ? alert('成功') : alert('失败'))
时小记,终有成。