uniApp使用ES6 promise await async请求封装

2,585 阅读1分钟

1、在根目录下创建public文件夹,创建http.js文件

const baseUrl = 'https://test.xiaomi.cn/api/'
const version = '2.4.2'
const http = {}
const httpRequest = (method, url, data) => {
	var promise = new Promise(function(resolve, reject) {
		uni.request({
			url: baseUrl + url + '?version=' + version,
			data: data,
			method: method,
			success: ((res) => {
				if (res.statusCode == 200) {
					if (res.data.errcode == 0) {
						resolve(res.data.data)
					} else {
						uni.showToast({
							title: res.data.errmsg,
							icon: 'noe'
						})
						resolve(res.data.data)
					}
				} else {
					reject(res.data.message)
				}
			}),
			fail: ((err) => {
				reject(err)
			}),
		})
	});
	return promise;
}

const httpGet = (url, data) => {
	return httpRequest('Get', url, data)
}
const httpPost = (url, data) => {
	return httpRequest('POST', url, data)
}

http.getProductList = (data) => {
	return httpPost('open/home/data', data)
}
export default http

2、在main.js里面引入,挂载到原型链上。

import http from '@/public/http.js'
Vue.prototype.http = http

3、在页面使用

async init() {
	      let data = { limit: 15, page: 1, zoneType: 6 };
		this.http.getProductList(data).then(function(resolve) {
		    console.log(resolve);
			});
		},