uniapp中关于api异步请求的转化问题

156 阅读1分钟

如果直接在代码中使用异步请求,在组件的其他位置是无法立即获取到实时数据的。

解决办法:

举例:使用uni-app的获取位置的请求uni.getLocation为例

1.封装uni.getLocation请求

async getL() {
	var Location
	return new Promise((resolve, reject) => {
		uni.getLocation({
			type: 'wgs84',
			success: function(res) {
				Location = res.longitude + "," + res.latitude
				resolve(Location)
			}
		})
	})
},

2.之后在需要使用的地方调用即可

async getlist() {
	await this.getL().then((res) => {
		this.Location =res  // 该数据就可以在组件其他位置使用了
	})
}