超级好用的 支付宝小程序 网络请求封装 async/await

此封装方法的优点:

1、实现async/await ; (小程序对async已经有非常好的支持,async也是目前公认的解决异步和回调地狱的终极解决方案)

2、具有高度的可配置性,不管你是定好的baseUrl,还是对接多个系统的Url都非常简单;

3、利用解构参数的特点使得参数的可读性非常强,极大降低后期维护成本,让所有请求变成一眼题;

4、遵循类名首字母大写的驼峰,实例驼峰的规则,也在一定程度上极大的降低维护成本;

5、可在底层做全局异常处理,感受一劳永逸的魅力;

1.在utils下新建 http.js

class HTTP {

  base_url = 'http://xxxx/' // 改成请求的地址

  get(url, data, config) {
    return this._request({
      url,
      data,
      config,
      method: 'GET'
    })
  }

  post(url, data, config) {
    return this._request({
      url,
      data,
      config,
      method: 'POST'
    })
  }

  static _isHttp(url) {
    return url.substr(0, 4).toLowerCase() === "http"
  }

  _request({ url, data, config, method }) {
    const token = my.getStorageSync({
      key: 'token', // 缓存数据的key
    }).data
    const is_http = HTTP._isHttp(url)
    // 未传入headers 
    let headers = {
      'content-type': 'application/json'
    }
    return new Promise((resolve, reject) => {
      my.request({
        headers: Object.assign(headers, {
          'X-Token': token || ''
        }),
        url: is_http ? url : this.base_url + url,
        data,
        method,
        ...config,
        success: (res) => {
          if (res.data.resultCode !== '200') {
            my.showToast({
              type: 'exception',
              content: res.data.message,
              duration: 2000
            });
          }
          resolve(res)
        },
        fail: (res) => {
          my.showToast({
            type: 'exception',
            content: '网络异常',
            duration: 2000
          });
          reject(res)
        }
      })
    })
  }
}

export { HTTP }

2.根目录新建一个文件夹modules,新建文件 modules/user.js,继承封装的http类

import { HTTP } from '../utils/http'

class UserModel extends HTTP {

  get_sms_code({
    appCode,
    mobile
  }) {
    console.log(this.x)
    return this.post('app_user/v1/get_sms_code', {
      appCode,
      mobile
    })
  }
}

export { UserModel }

3.页面中使用 如pages/login.js

import { UserModel } from '../../modules/user'
const userModel = new UserModel()

Page({

    onLoad(){
      this.get_sms_code()
    },
    
    async get_sms_code() {
      const res = await userModel.get_sms_code({
        appCode: '123456',
        mobile: '157xxx40150'
      })
     console.log(res)
  }

})
原文地址:https://www.cnblogs.com/likewpp/p/11653949.html