小程序:将 wx.request 封装为 promise

具体封装如下 :

class Request {
  constructor (parms) {
    this.withBaseURL = parms.withBaseURL
    this.baseURL = parms.baseURL
  }
  get (url, data) {
    return this.request('GET', url, data)
  }
  post (url, data) {
    return this.request('POST', url, data)
  }
  put (url, data) {
    return this.request('PUT', url, data)
  }
  request (method, url, data) {
    const vm = this
    return new Promise((resolve, reject) => {
      wx.request({
        url: vm.withBaseURL ? vm.baseURL + url : url,
        data,
        method,
        success (res) {
          resolve(res)
        },
        fail () {
          reject({
            msg: '请求失败',
            url: vm.withBaseURL ? vm.baseURL + url : url,
            method,
            data
          })
        }
      })
    })
  }
}

const request = new Request({
  baseURL: 'http://test',
  withBaseURL: true
})

module.exports = request

调用

const http = require('../../unitl/http')

libs.request.get('url', data})
.then(res => {
  console.log(res)
})
.catch(e => {
  console.log(e)
})

你可能感兴趣的:(小程序:将 wx.request 封装为 promise)