简介
一层一层的用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是异步的。