小程序封装请求+防抖

`//接口请求封装

let config = require('./config.js');

function request_fn(params) {

wx.showNavigationBarLoading()

const url = ${config.config.url}${params.url}

var header = {

'content-type': 'application/x-www-form-urlencoded'

}

return new Promise(function (resolve, reject) {

wx.request({

  url: url,

  method: params.method || "post",

  data: params.data || {},

  header: header,

  success: (res) => {

    if(res.statusCode == 200 ){

      resolve(res)

    } else{

      wx.showToast({

        title: '网络异常,请稍后再试!gdefail1',

        icon: 'none',

        duration: 2000,

        mask: true

      })

      reject(res)

    }

  },

  fail: function (res) {  

    wx.showToast({
      title: '网络异常,请稍后再试!gdefail2',
      icon: 'none',
      duration: 2000,
      mask: true
    })

    reject(res)

  },
  complete: function () {

    wx.hideLoading()

    wx.hideNavigationBarLoading()

  }
})

}).catch(res => {

reject(res)

})
}`

gdefail1、gdefail2 标识字段--- 用于判断接口是否报错(前后端那块出问题)

`/* 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 new Promise((resolve, reject) => {
request_fn(params).then(res => {
resolve(res)
})
})
}
}`

导出:

`module.exports = {

axios: request

}`

全局自定义请求变量(app.js里):

`let request = require('utils/request.js')

App({
axios: request .axios,
})`

使用:

`
const app = getApp()//引入

getImg(e){

var that = this

app.axios({

  url: '****',

  data: {

    cardMemberId: wx.getStorageSync('id'),

    tenantId: e.currentTarget.dataset.id

  }
}).then(res => {

  if (res.data.message.type == 'success') {

        //do some thing
  }
})

}`

posted @ 2020-05-13 14:02  前端小小小怪  阅读(755)  评论(0编辑  收藏  举报