关于uni-app 中 使用async + await 将异步请求同步化

hykeda6年前Vue2125

这段时间在使用uni-app开发小程序,希望在页面加载时,获取地区数据,然后展示到页面上。

一开始写在了onLoad方法上,发现页面加载时,用异步uni.request方法获取数据,当页面加载完后,异步方法还未获取到数据,赋值给变量的时候是空值。

代码片段:

onLoad() {
	uni.request({
		url: url,
		data: {},
		method:'GET',
		header: {
			'Access-Control-Allow-Origin':'*'
		},
		success: (result) => {
			try {
				uni.setStorageSync('storage_area', JSON.parse(result.data.items));
				this.arealist = JSON.parse(res.data.items);
			} catch (e) {
				// error
			}
	
		},
		fail: (e) => {
			res(e);
		}
	})
}

在这里 arealist 这个变量赋值过程延时,导致页面上展示的时候是空。

解决这个问题 使用 异步方法同步化 async和await关键字

onLoad(){
	this.setAreaList();
},
methods: {
	async setAreaList(){ //这里使用异步关键字
		let area = await this.areaCache(); //这里使用了await 会等待areaCache这个方法返回数据后才会去执行下面的代码
		
	        console.log(area);
	}
}

areaCache方法必须返回的是一个Promise对象

areaCache:function(){
	return new Promise((res) => {
		try {
			const value = uni.getStorageSync('storage_area');
			if (value) {
				res(value);
			}else{
				uni.request({
					url: url,
					data: {},
					method:'GET',
					header: {
						'Access-Control-Allow-Origin':'*'
					},
					success: (result) => {
						try {
							uni.setStorageSync('storage_area', JSON.parse(result.data.items));
							res(JSON.parse(result.data.items));
						} catch (e) {
							// error
						}
				
					},
					fail: (e) => {
						res(e);
					}
				})
			}
			
		} catch (e) {
			// error
		}
	})
}

注意点:这里的 async 和 await 必须成对出现 不然会报错。

相关文章

Vue3 Pinia持久化存储

一、Pinia持久化存储二、使用步骤1.安装插件代码如下(示例):npm i pinia-plugin-persist --save2.store/index.js代码如...

vue3项目,Element-plus ElMessage API 调用样式丢失问题

1、Element-plus使用了自动按需导入,vite.config.js配置如下:defineConfig({     plugins: [...

使用vite打包vue项目生成dist文件夹,部署至nginx除了index.html,其他路径都提示404错误的解决

使用vite打包vue项目生成dist文件夹,部署至nginx除了index.html,其他路径都提示404错误的解决

用vue打包生成dist文件夹,然后在本地nginx部署vue项目时只能访问默认页面,刷新和跳转页面都会出问题。原因:只访问了dist文件下的 index.html、index.htm页面,...

[Vue warn]: Error in render: “TypeError: Cannot read property ‘name‘ of undefined“,报错,已解决。

含义:渲染时发生错误:类型错误:不能读取undefined的name属性原因:出现上述报错其实是因为,你访问了undefined.name,但是 undefined 没有 name,所以报错。原因有两...

前端常用的UI组件库

Arco DesignTaro UISemi DesignAnt DesignElementView DesignVantLayui-vueFusion Design1. Arco Desi...

Vue2.x笔记

vue2.0 开始不能挂载到<html> 或者 <body> 上。 transition 动画过渡的时候,如果是:<transit...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。