Vue 多次尝试请求ajax

javascript 复制代码
const attemptWithRetries = async(attempts:number, maxRetries: number, count:number) => {
    if(attempts < maxRetries)
    {
        try {
        const param = {
        userid: userid,
        };
        await testApi.getTestList(param).then((res:any) => {
            if(res.length > 0){
                // 处理成功操作
            }
            
        });

        if(attempts < maxRetries)
        {
			// 未到请求次数,抛出异常,接收异常位置再次发起请求
            throw new Error('Request failed');
        }

        } catch (error) {
            setTimeout(() => {
                attempts++
                attemptWithRetries(attempts,maxRetries,count); // 递归调用
            }, 1000); // 等待 1 秒后重试
        }
    }
}

// 调用
 let attempts = 0;
 let maxRetries = 5;       
 attemptWithRetries(attempts,maxRetries,count);

上方代码是尝试五次请求ajax的代码。

注意:ajax请求,要使用async和await,保证一个ajax请求完成后再发起新的尝试,不然会一次性请求五次ajax,不友好

相关推荐
林的快手1 小时前
CSS列表属性
前端·javascript·css·ajax·firefox·html5·safari
匹马夕阳2 小时前
ECharts极简入门
前端·信息可视化·echarts
API_technology2 小时前
电商API安全防护:JWT令牌与XSS防御实战
前端·安全·xss
yqcoder2 小时前
Express + MongoDB 实现在筛选时间段中用户名的模糊查询
java·前端·javascript
liaojuajun2 小时前
axios
ajax
十八朵郁金香3 小时前
通俗易懂的DOM1级标准介绍
开发语言·前端·javascript
计算机-秋大田3 小时前
基于Spring Boot的兴顺物流管理系统设计与实现(LW+源码+讲解)
java·vue.js·spring boot·后端·spring·课程设计
m0_528723814 小时前
HTML中,title和h1标签的区别是什么?
前端·html
Dark_programmer4 小时前
html - - - - - modal弹窗出现时,页面怎么能限制滚动
前端·html
GDAL4 小时前
HTML Canvas clip 深入全面讲解
前端·javascript·canvas