api接口请求失败重复请求
前端开发中可能遇到的一个情况,要求一个api接口请求失败后重复再调用,并且规定调用的次数。
下面是重复请求的函数,返回一个promise。主要思路:使用while循环,内部使用try catch。 当请求失败时,times 值不为0就重新开始循环,请求成功就结束循环。
/*
fn: promise
params: fn的参数
times: 需要重复发起请求的次数
*/
const retry = (fn, params: object, times: number) => {
return new Promise(async (resolve, reject) => {
while (times--) {
try {
const res = await fn(params);
resolve(res);
break;
} catch (error) {
if (times <= 0) {
reject(error);
}
}
}
});
};
具体使用
// 业务接口
const getData = params => {
return axios.get('xxxx/xxxx', {params: params})
}
// 成功就返回数据,失败就重复请求,超过3次失败就返回失败
retry(getData, params, 3)
.then(res => {})
.catch(err => {})
如上,简单的一个失败重复请求就完成了。