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,不友好

相关推荐
GIS之路7 分钟前
GeoTools 结合 OpenLayers 实现属性查询(二)
前端·信息可视化
烛阴15 分钟前
一文搞懂 Python 闭包:让你的代码瞬间“高级”起来!
前端·python
AA-代码批发V哥18 分钟前
HTML之表单结构全解析
前端·html
聪聪的学习笔记29 分钟前
【1】确认安装 Node.js 和 npm版本号
前端·npm·node.js
小磊哥er41 分钟前
【前端工程化】你知道前端编码规范包含哪些内容吗
前端
菌菇汤1 小时前
uni-app实现单选,多选也能搜索,勾选,选择,回显
前端·javascript·vue.js·微信小程序·uni-app·app
Ramos丶1 小时前
【ABAP】 从无到有 新建一个Webdynpro程序
java·前端·javascript
qq_411671981 小时前
vue3 的模板引用ref和$parent
前端·javascript·vue.js
清幽竹客2 小时前
vue-37(模拟依赖项进行隔离测试)
前端·vue.js
vvilkim2 小时前
Nuxt.js 页面与布局系统深度解析:构建高效 Vue 应用的关键
前端·javascript·vue.js