uni-app中使用 async + await 实现异步请求同步化

问题:
在uni-app中,uni.request等网络请求都是异步的,直接使用可能会导致页面渲染完毕时,数据还未成功获取的情况。
解决方法:

<script>
export default {
	data() {
		return {};
	},
	methods:{
		getOutInfo(){ 
			return new Promise((resolve, reject) => {
				uni.request({ 
					url : `请求地址`,
					method : "GET",
					data : {},
					success: (res) => {
						console.log(res)
            			resolve('suc');  // 千万别忘写!!!
					},
					fail:(err)=>{
						reject('err')
					}
				})
			})
		},
		async mountDealCount(){
			await this.getOutInfo()
			console.log('我在数据获取之后执行')
		}
	},
	beforeMount(){
		this.mountDealCount()
	}
}
</script>

效果:
在这里插入图片描述
注意:当调用的级数增加的时候,需要逐级的增加async和await

<script>
export default {
	methods:{
		getOutInfo(){ 
			return new Promise((resolve, reject) => {
				uni.request({ 
					url : `请求地址`,
					method : "GET",
					data : {},
					success: (res) => {
						console.log(res)
            			resolve('suc');  // 千万别忘写!!!
					},
					fail:(err)=>{
						reject('err')
					}
				})
			})
		},
		async dealInfo(){
			await this.getOutInfo()
			console.log('我在数据获取之后执行')
		},
		async loadDeal(){
			await this.dealInfo()
			console.log('我在 dealInfo 之后执行')
		}
	},
	beforeMount(){
		this.loadDeal()
	}
}
</script>

总结:

  1. 将uni.request请求封装在Promise构造函数中;
  2. 使用async + await;
  • 22
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
uni-app 使用 async/await 主要有以下几个步骤: 1. 将需要异步处理的函数改为 async 函数,并在其使用 await 关键字等待异步操作完成。 2. 在调用 async 函数的地方使用 try/catch 块处理可能出现的异常。 下面是一个使用 async/await 的例子: ```javascript // 定义一个异步函数 async function getData() { const res = await uni.request({ url: 'https://some-api.com/data', method: 'GET' }); if (res[0]) { return res[1]; } else { throw new Error('请求失败'); } } // 在调用 getData 的地方使用 try/catch 块处理可能出现的异常 try { const data = await getData(); console.log(data); } catch (err) { console.error(err); } ``` 在上面的代码,`getData` 函数使用了 `await` 等待 `uni.request` 异步操作完成。在使用 `getData` 函数时,我们使用了 try/catch 块来处理可能出现的异常。 需要注意的是,`async` 函数返回的是一个 `Promise` 对象,因此,在使用 `async` 函数时,我们可以将其返回值赋值给一个变量,并使用 `then` 方法获取异步操作的结果,如下所示: ```javascript async function getData() { const res = await uni.request({ url: 'https://some-api.com/data', method: 'GET' }); if (res[0]) { return res[1]; } else { throw new Error('请求失败'); } } getData().then(data => { console.log(data); }).catch(err => { console.error(err); }); ``` 上面的代码,我们使用 `then` 方法获取 `getData` 函数的异步结果,并使用 `catch` 方法处理异常。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明天也要努力

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值