Uniapp中request的promise封装及快速调用

简介

一层一层的用promise属实烦人,又去网上找了被人的封装方法,发现大多数都并不适合自己,因此笔者将uni.request封装了起来,可以更加合理调用。

快速上手

promise代码封装

首先,您需要为您的项目创建两个文件,如下图所示。
在这里插入图片描述

  • API用于保存所有的请求
  • request用于封装请求
  • API.js
export default {
	get_device_info: 'API/getOpendoorInfo', 
}
  • request.js
const baseURL = 'http://localhost:8080/'//请求服务器公共地址

//页面中想用.then()就必须是Prnmise实例
export default {
	request(options){
		const {
			api,
			url,
			data,			
		} = options;
		let httpDefaultOpts = {
			url: baseURL + url,
			method: 'POST',
			dataType: 'json',
		}
		if (data && data !== '') httpDefaultOpts['data'] = options.data
		return new Promise((resolve,reject)=>{//把调取的的接口给了一个Promise实例
			uni.request(httpDefaultOpts).then((res) => {
				console.log('[request info] ' + JSON.stringify(httpDefaultOpts))
				console.log('[response info] ' + JSON.stringify(res[1]))
                  let resCode = res[1].data['code']
                  if (resCode == 20000) {
                      resolve(res[1].data['data'])
                      //resolve(JSON.stringify(res[1]))	
                      //如果返回的不是20000
                  }else{
                      reject(res[1].data['data'])
                  }
			})
		})
	},
	//get方法
	get(options){
		options.method="get"
		return this.request(options)
	},
	//post方法
	post(options){
		options.method="post"
		return this.request(options)
	}
	
}
  • main.js
import request from '@/common/request.js'
import API from '@/common/API.js'
Vue.prototype.$api = API
Vue.prototype.$request=request

需要说明的是,该方式的封装不适用与restful风格的API。

调用封装

单个request调用
this.$request.get({
	url: this.$api.get_device_info+"?recentOpenUserId=2"
}).then(res=>{
	// res为json字符串
	console.log('[info] res is :'+res)
	this.mydata = res['data']
},error=>{
	console.log(`[error] ${error}`)
})

注意事项:如果封装的request中直接返回json格式的数据,我们使用then函数调用的时候只能获取到object格式的数据,因此我们不如直接返回string格式的字符串,返回回来的时候也是string格式,这个时候我们对这个字符串进行json解析就可以了。

多个request调用

多个request调用相当于多个promise进行调用,可以集体进行处理,避免回调地域等问题的出现。

  • 示例
	let that = this	
	let p1 = that.$http.post({
		url: that.$api.get_my_activity_run_count,
		data: {
			userId: that.userId
		}
	})
	let p2 = that.$http.post({
		url: that.$api.get_my_activity_run_count,
		data: {
			userId: that.userId
		}
	})
	let p3 = that.$http.post({
		url: that.$api.page_publish_count,
		data: {
			userId: that.userId
		}
	})

	// 一起返回信息
	Promise.all([p1, p2, p3]).then(res => {
		//['成功了', 'success']
		console.log(`[info] all res :${JSON.stringify(res)}`)
		that.userInfo = res[0]
		that.runingActivityNum = res[1]
		that.allActivityNum = res[2]
	},error=>{
        console.log(`[error] ${error}`)
    })

舒服了~

异常处理

promise可以使用catch进行异常处理,也可以使用reject传递给下一级处理,这里推荐使用reject传递的给下一级做处理,因为reject是异步的。

参考资料

Promise 失败和捕捉以及异步报错

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Zeeland

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

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

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

打赏作者

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

抵扣说明:

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

余额充值