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

相关推荐
li35745 小时前
将已有 Vue 项目通过 Electron 打包为桌面客户端的完整步骤
前端·vue.js·electron
Icoolkj6 小时前
VuePress 与 VitePress 深度对比:特性、差异与选型指南
前端·javascript·vue.js
excel6 小时前
CNN 分层详解:卷积、池化到全连接的作用与原理
前端
excel6 小时前
CNN 多层设计详解:从边缘到高级特征的逐层学习
前端
西陵7 小时前
Nx带来极致的前端开发体验——任务编排
前端·javascript·架构
大前端helloworld7 小时前
从初中级如何迈入中高级-其实技术只是“入门卷”
前端·面试
东风西巷9 小时前
Balabolka:免费高效的文字转语音软件
前端·人工智能·学习·语音识别·软件需求
萌萌哒草头将军9 小时前
10个 ES2025 新特性速览!🚀🚀🚀
前端·javascript·vue.js
半夏陌离9 小时前
SQL 入门指南:排序与分页查询(ORDER BY 多字段排序、LIMIT 分页实战)
java·前端·数据库