request请求封装基于promise。
request请求接口函数:
//接口请求封装
function request_fn(params) {
const app = getApp();
wx.showLoading({
title: '加载中',
mask: true
})
wx.showNavigationBarLoading()
const url = `${app.globalData.server}?i=1&r=${params.url}`
const token = wx.getStorageSync("token")
var header = {
'content-type': 'application/x-www-form-urlencoded'
}
if (token != "" && token != null) {
header['X-TOKEN'] = token
}
return new Promise(function (resolve, reject) {
wx.request({
url, header,
method: params.method || "POST",
data: params.data || {},
success: (res) => {
if (res.data.error !== 0 || res['statusCode'] !== 200) {
toast('系统开小差啦,请稍后再试', 3000)
}
resolve(res.data)
},
fail: function (res) {
toast('系统开小差啦,请稍后再试', 3000)
reject(res.data)
},
complete: function () {
wx.hideLoading()
wx.hideNavigationBarLoading()
}
})
}).catch(res => {
reject(res)
})
}
请求函数加入防抖功能:有两种防抖效果,根据自己需求使用
/* ajax防抖 */
var timeOut = null
function request(params) {
let shake = params.shake || false // 是否防抖
let shakeTime = params.shakeTime || 300 //默认防抖时间300毫秒
if (shake) {
return new Promise((resolve, reject) => {
timeOut && clearTimeout(timeOut)
/* 第一种防抖效果:防抖时间内只执行第一次触发 */
// let timer = !timeOut
// if (timer) {
// request_fn(params).then(res => {
// resolve(res)
// })
// }
// timeOut = setTimeout(() => {
// timeOut = null
// }, shakeTime)
/* 第二种防抖效果:防抖时间内停止触发后执行 */
timeOut = setTimeout(() => {
request_fn(params).then(res => {
resolve(res)
})
}, shakeTime)
})
}else {
return request_fn(params)
}
}
最后导出函数
module.exports = request
页面中使用函数:先在app.js引用,方便调用
//app.js
import util from './utils/util.js'
import api from './utils/api.js'
App({
api: api,
axios: util.request, // 本人比较懒,敲axios比敲util.request方便哈哈哈哈哈哈嗝~
onLaunch: function() {
},
})
调用
const app = getApp()
Page({
submit(){
console.log('按钮触发事件');
app.axios({
url: your api,
shake: true, // 设置防抖
data: {
your data
}
}).then(res=>{
console.log('请求完成');
})
}
})
看下防抖效果(上图)
END!.