使用promise封装小程序网络请求

请求接口数据:

module.exports = {
  request: (params = {url, data}) => {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    return new Promise((resolve, reject) => {
      wx.request({
        url: BaseUrl + params.url,
        data: params.data || {},
        header: {
            'Content-Type': 'application/x-www-form-urlencoded',
            // 如果有接口鉴权
            'SIGN': getSign(params.data),
            'APPKEY': ''
        },
        method: 'post',
        success: (resp) => {
          // 根据实际业务调用resolve或者reject
        },
        fail: (err) => {
          console.log(err);
          reject(err)
        },
        complete: () => {
          wx.hideLoading();
        }
      })
    })
  },
}

项目中会有很多接口,我们可以根据功能模块,再独立封装。比如登录,可以新增一个login.js:

const {request} = require('request.js');

module.exports = {
  login: () => {
    // ...
  },

  logout: () => {
    // ...
  }
}

文件上传:


module.exports = {
  upload: ({count = 9, mediaType = ['image', 'video'], sizeType = ['original', 'compressed']} = {}) => {
    return new Promise((topResolve, topReject) => {
      wx.chooseMedia({
        count: count,
        mediaType: mediaType,
        sizeType: sizeType,
        success(res) {
          const {tempFiles} = res
          const all = [];
          for(let i in tempFiles) {
            all.push(new Promise((resolve, reject) => {
                var upTask = wx.uploadFile({
                  url: BaseUrl + 'upload api'
                  filePath: tempFiles[i].tempFilePath,
                  name: '',
                  formData: {},
                  success: (result) => {
                    resolve(JSON.parse(result.data));
                  },
                  fail: (err) => {
                    reject(err);
                  }
                });
              })
            )
          }
          
          Promise.all(all).then(results => {
            topResolve(results);
          }).catch(err => {
            console.log(err);
            topReject(err)
          })
        }
      })
    })
  }
}