uni-app:实现request请求的递归(设置request请求的访问次数),并且调用自定义方法给出返回值

一、效果展示

失败效果

成功效果

二、写入后端请求部分

分析

①自定义一个模块common.js主要用于封装所有的请求函数
②核心代码
javascript 复制代码
function requestWithRetry(cmd, username, password, retryCount) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: ip + 'sys/user/login',
			data: {
				cmd: cmd,
				usrname: username,
				passwd: password
			},
			method: 'POST',
			dataType: 'json',
			header: {
				"content-type": "application/json"
			},
			success: res => {
				// 存入全局变量中
				getApp().globalData.username = username;
				getApp().globalData.password = password;
				getApp().globalData.access_token = res.data.access_token;
				getApp().globalData.loginmode = loginmode;
				console.log(`第 ${retryCount} 次请求成功:`, res.data);
				resolve(res.data);
			},
			fail(err) {
				console.error(`第 ${retryCount} 次请求失败,剩余重试次数 ${retryCount - 1}:`, err)
				if (retryCount <= 1) {
					// 重试次数已经用完,将错误信息返回给调用者
					reject(new Error('请求失败'))
				} else {
					// 还有重试次数,继续重试
					setTimeout(() => {
						requestWithRetry(cmd, username, password,
							retryCount - 1).then(resolve).catch(reject)
					}, 500)
				}
			}
		});
	});
}
// 调用方法,retryCount 为重试次数
return requestWithRetry(cmd, username, password, 3)
	.then(data => {
		// console.log('请求成功', data);
		return data;
	})
	.catch(error => {
		// console.log('请求失败', error);
		throw error;
	});

完整代码

javascript 复制代码
//定义全局变量
const ip = 'XXXX';
//定义全局函数
//生成随机三位数 
function generateRandomNumber() {
	var min = 100;
	var max = 999;
	var randomNumber = Math.floor(Math.random() * (max - min + 1) + min);
	return randomNumber;
}
//http方式进行登录
function login_httpmode(username, password, cmd, loginmode) {
    //http
    if (loginmode == 'http') {
        function requestWithRetry(cmd, username, password, retryCount) {
            return new Promise((resolve, reject) => {
                uni.request({
                    url: ip + 'sys/user/login',
                    data: {
                        cmd: cmd,
                        usrname: username,
                        passwd: password
                    },
                    method: 'POST',
                    dataType: 'json',
                    header: {
                        "content-type": "application/json"
                    },
                    success: res => {
                        // 存入全局变量中
                        getApp().globalData.username = username;
                        getApp().globalData.password = password;
                        getApp().globalData.access_token = res.data.access_token;
                        getApp().globalData.loginmode = loginmode;
                        console.log(`第 ${retryCount} 次请求成功:`, res.data);
                        resolve(res.data);
                    },
                    fail(err) {
                        console.error(`第 ${retryCount} 次请求失败,剩余重试次数 ${retryCount - 1}:`, err)
                        if (retryCount <= 1) {
                            // 重试次数已经用完,将错误信息返回给调用者
                            reject(new Error('请求失败'))
                        } else {
                            // 还有重试次数,继续重试
                            setTimeout(() => {
                                requestWithRetry(cmd, username, password,
                                    retryCount - 1).then(resolve).catch(reject)
                            }, 500)
                        }
                    }
                });
            });
        }
        // 调用方法,retryCount 为重试次数,设置最大次数为三次
        return requestWithRetry(cmd, username, password, 3)
            .then(data => {
                // console.log('请求成功', data);
                return data;
            })
            .catch(error => {
                // console.log('请求失败', error);
                throw error;
            });
    }
}
//导出
module.exports = {
	ip,
	generateRandomNumber,
	login_httpmode,
}

三、进行方法的调用

核心代码

javascript 复制代码
common.login_httpmode(username, password, cmd, type)
	.then(info => {
		console.log("请求成功",info)		
	})
	.catch(error => {
		console.log("请求失败",error)		
	});

完整代码

javascript 复制代码
//执行加载中的效果
uni.showLoading({
	title: '正在登录...',
	mask: true,
});
//调用登录方法
common.login_httpmode(username, password, cmd, type)
     //成功返回
	.then(info => {
		console.log("请求成功",info)
		if (info.success == true) {	
            uni.hideLoading(); // 隐藏加载提示
			//全局变量中的数据 
			uni.reLaunch({ //跳转到主页
				url: '/pages/mine/mine_index/mine_index'
			})
		} else {
			uni.hideLoading(); // 隐藏加载提示
			if (info.msg == 'pass err') {
				uni.showToast({
					title: '账号密码不正确',
					icon: 'none'
				})
			}
		}
	})
	.catch(error => {
		console.log("请求失败",error)
		uni.showToast({
			title: '登录失败',
			icon: 'none'
		})
	});
相关推荐
iOS阿玮2 小时前
打个广告,帮忙招一个iOS开发的扛把子~
uni-app·app·apple
Cerrda3 小时前
🌟让你的uniapp应用拥有更现代的交互体验,一个支持滚动渐变透明的导航栏组件🌟
uni-app
2501_916007474 小时前
iOS 应用性能测试的工程化流程,构建从指标采集到问题归因的多工具协同测试体系
android·ios·小程序·https·uni-app·iphone·webview
00后程序员张7 小时前
iOS 抓不到包怎么办?从 HTTPS 解密、QUIC 排查到 TCP 数据流分析的完整解决方案
android·tcp/ip·ios·小程序·https·uni-app·iphone
前端互助会7 小时前
UNI-APP开发APP避坑指南:这些关键事项你必须掌握
uni-app
游戏开发爱好者81 天前
iOS 商店上架全流程解析 从工程准备到审核通过的系统化实践指南
android·macos·ios·小程序·uni-app·cocoa·iphone
toooooop81 天前
Vuex 中 state、mutations 和 actions 的原理和写法
前端·javascript·uni-app
林_xi1 天前
uniapp使用@uni-ku/root插件实现全局组件
前端·uni-app
计算机毕设定制辅导-无忧学长1 天前
基于uni-app的“民族风韵”特色购物小程序
uni-app
一个处女座的程序猿O(∩_∩)O1 天前
UniApp 生命周期全解析:从应用到页面,再到组件的完美协奏曲
前端·uni-app