使用Promise对uni.request进行封装
为什么需要封装想用Promise,而uni.request并不返回Promise请求方法逻辑类似,可以写一个公共的请求方法封装原方法// 轮播图请求getSwiperdata() {this.request()},// 公共请求方法request() {uni.request({url: 'https://www.uinav.com/api/public/v1/home/swiperdata',
·
为什么需要封装
- 想用Promise,而uni.request并不返回Promise
- 请求方法逻辑类似,可以写一个公共的请求方法
封装
- 原方法
// 轮播图请求
getSwiperdata() {
this.request()
},
// 公共请求方法
request() {
uni.request({
url: 'https://www.uinav.com/api/public/v1/home/swiperdata',
success: res => {
console.log(res);
// 当状态码正确时,才获取数据
let { meta, message } = res.data;
if (meta.status === 200) {
this.swiperdata = message;
}
}
});
}
- promise封装
- 请求参数可能会有很多,必须是一个对象
- 在公共请求方法里面,获取url
getSwiperdata() {
//this.request会返回promise对象
this.request({
url: 'https://www.uinav.com/api/public/v1/home/swiperdata',
}).then(data=>{
//data就是封装里面resolve里面的messaeg
this.swiperdata = data
})
},
// 公共请求方法
request(options) {
return new Promise((resolve, reject) => {
// 在Promise的构造函数里面放异步任务
uni.request({
url: options.url,
success: res => {
console.log(res);
// 当状态码正确时,才获取数据
let { meta, message } = res.data;
if (meta.status === 200) {
// 当请求返回正确数据时,resolve
resolve(message)
}
}
});
});
}
resolve
作用是,将Promise对象
的状态从“未完成”变为“成功”(即从 pending 变为 resolved),在异步操作成功时调用,并将异步操作的结果,作为参数传递出去;reject
作用是,将Promise对象
的状态从“未完成”变为“失败”(即从 pending 变为 rejected),在异步操作失败时调用,并将异步操作报出的错误,作为参数传递出去。
使用async 和 await
- await修饰promise对象,会返回
promise.then
的数据 - async:有await的语句的function必须用async修饰
async getSwiperdata() {
//await修饰promise对象,返回数据相当于promise.then的形参
let data = await this.request({
url: 'https://www.uinav.com/api/public/v1/home/swiperdata',
})
this.swiperdata = data
},
公共请求方法希望给到其他页面使用,
- 公共请求方法抽取出来作为一个模块
utils/request.js
- 其他页面需要request方法时,引入即可
- request.js
const BASE_URL = 'http://localhost:3000/api'
const common = {
baseUrl: BASE_URL,
data: {},
header: {
'content-type': 'application/json',
'content-type': 'application/x-www-form-urlencoded'
},
method: 'GET',
dataType: 'json',
isShowLoading: true
}
export default request = (options = {}) => {
options.url = BASE_URL + options.url
options.data = options.data || common.baseUrl
options.header = options.header || common.header
options.method = options.method || common.method
options.dataType = options.dataType || common.dataType
options.isShowLoading = options.isShowLoading || common.isShowLoading
if (options.isShowLoading) {
uni.showLoading({
title: '加载中...'
})
}
return new Promise((resolve, reject) => {
uni.request({
...options,
success: res => {
console.log('res', res)
if (res.statusCode !== 200) {
return reject()
}
return resolve(res.data)
},
fail: rej => {
uni.showLoading({
title: '网络请求错误'
})
return
},
complete: () => {
if (options.isShowLoading) {
uni.hideLoading()
}
}
})
})
}
//home.vue引入request
import request from '@/utils/request'
- 全局引入
//main.js
import request from '@/utils/request';
// 把request方法挂载到Vue原型上
Vue.prototype.$request = request
//home.vue
this.$request
- 调用使用
this.$request
更多推荐
所有评论(0)