封装一个请求事件
在写小程序的时候, 避免不了老是要写请求事件, 既然如此 为什么不封装一个请求只要填写参数就 然后挂载在 app.js里面全局使用
这个文件写好之后封装在一个文件里面直接 export 导出使用
// 加上 complete 事件
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;
}
);
}
);
}
http(info) {
return new Promise((resolve, reject) => {
wx.request({
url: 'https:www.baidu.com/xxx/xxx'+ info.url,
data: info.data || {},
header: {
"content-type": "application/x-www-form-urlencoded" // 设置请求头
},
success: function(res) {// 请求成功发起的回调
resolve && resolve(res.data)
},
fail: function(res){// 请求失败发起的回调
reject && reject(res.data)
},
complete: function(res){// 不管成功或者失败都会发起回调
failFun&& failFun(res);
}
})
})
}
// 导出使用
module.exports = {
http
}
在想要使用请求的页面当中 new 一个超全局变量 然后调用我们刚刚创建好的方法
import { http } from '文件地址'
Page({
onload(opstion){
http({
url: '请求接口的地址',
data: {
// 参数
}
}).then(res => {
console.log('成功')
}).catch(() => {
console.log('失败')
}).finally(() => {
console.log('无论失败还是成功都会触发')
})
}
})
这样就可以随时使用 请求的方法了 改动的时候只需要改动一处 不需要到处找来代码来修改啦~