代码敲得再六又怎么样...

小程序使用Promise封装API请求

88 2020-12-16 08:51:24
// 服务端api地址
const API_BASE_URL = 'https://www.bigfool.cn/api'
const request = (url, method, data,isLoad=true) => {
	if (isLoad) {
		wx.showLoading({
		title: '加载中...',
		})
	}
	// api_token
	let api_token = wx.getStorageSync('api_token')
	// 请求地址
	let _url = API_BASE_URL + url
	return new Promise((resolve, reject) => {
		wx.request({
			url: _url,
			method: method,
			data: data,
			header: {
			'Token': api_token,
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		success(req) {
			if (req.data.code == 200) {
				resolve(req.data)
			} else if (req.data.code == 4001) {
				wx.navigateTo({
				url: '/pages/login/login?page='+'/pages/my/my',
				})
			} else {
				wx.showToast({
					title: req.data.msg ? req.data.msg : '请求出错',
					icon: 'none',
					// image:'/image/error.png',
					duration: 2000
				})
			}
		return false;
		},
		fail(error) {
			reject(error)
		},
		complete(com) {
			if (isLoad) {
				wx.hideLoading()
			}
		}
	})
	})
}

/**
* 小程序的promise没有finally方法,自己扩展下
*/
Promise.prototype.finally = function (callback) {
	var Promise = this.constructor;
	return this.then(
		function (value) {
			Promise.resolve(callback()).then(
				function () {
					return value;
				}
			);
		},
		function (reason) {
			Promise.resolve(callback()).then(
				function () {
					throw reason;
				}
			);
		}
	);
}

module.exports = {
	request,
	// 登录授权
	login: (data) => {
		return request('/wxlogin', 'post', data)
	},
}