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

相关推荐
二哈喇子!2 小时前
BOM模型
开发语言·前端·javascript·bom
二哈喇子!2 小时前
Vue2 监听器 watcher
前端·javascript·vue.js
yanyu-yaya2 小时前
前端面试题
前端·面试·前端框架
二哈喇子!3 小时前
使用NVM下载Node.js管理多版本
前端·npm·node.js
GGGG寄了3 小时前
HTML——文本标签
开发语言·前端·html
2501_944521594 小时前
Flutter for OpenHarmony 微动漫App实战:推荐动漫实现
android·开发语言·前端·javascript·flutter·ecmascript
Amumu121384 小时前
Vue核心(三)
前端·javascript·vue.js
CoCo的编程之路5 小时前
2026 前端效能革命:如何利用智能助手实现“光速”页面构建?深度横评
前端·人工智能·ai编程·comate·智能编程助手·文心快码baiducomate
RFCEO5 小时前
HTML编程 课程五、:HTML5 新增语义化标签
前端·html·html5·跨平台·语义化标签·可生成安卓/ios·html最新版本
2501_944521595 小时前
Flutter for OpenHarmony 微动漫App实战:图片加载实现
android·开发语言·前端·javascript·flutter·php