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

相关推荐
烈风逍遥7 分钟前
第七篇:提示词模板管理与 Agent 提示词编排
前端·人工智能·后端
Amos_Web17 分钟前
Rspack 源码解析(十二):JavaScript Chunk 是如何被渲染出来的
前端·rust·源码
前端探险家Rick26 分钟前
React Native 二级弹出面板 + 键盘适配:从踩坑到正确方案
前端
用户9210802628630 分钟前
MCP 是什么?用 Figma MCP 辅助还原 Vue 页面
前端
用户9210802628630 分钟前
用 Figma MCP 还原 Vue 页面时,我遇到的三个问题
前端
修罗王31 分钟前
从 React Bits 到 Vue/Svelte Bits:重新定义前端“视觉表达层“
前端
kiros_wang32 分钟前
Notification 本地通知:定时消息、点击路由跳转、桌面角标适配
前端
计算机毕设定制辅导-无忧学长36 分钟前
《基于Vue的流浪动物救助中心管理系统的设计与实现》
java·vue.js·spring boot·流浪动物救助中心管理系统
flash俊杰39 分钟前
SQLite + sqlite-vec:100 篇文档内的私域知识库怎么做
前端