码迷,mamicode.com
首页 > 微信 > 详细

微信小程序request(promise)方法封装

时间:2018-06-09 11:41:29      阅读:548      评论:0      收藏:0      [点我收藏+]

标签:exp   微信小程序   ace   encode   应用   post方法   false   final   UI   

var Promise = require(‘es6-promise‘);
var app = getApp();

function wxPromisify(fn) {
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        //成功
        resolve(res)
      }
      obj.fail = function (res) {
        //失败
        reject(res)
      }
      fn(obj)
    })
  }
}
//无论promise对象最后状态如何都会执行
Promise.prototype.finally = function (callback) {
  let P = this.constructor;
  return this.then(
    value => P.resolve(callback()).then(() => value),
    reason => P.resolve(callback()).then(() => { throw reason })
  );
};


/**
 * 微信请求get方法
 * url
 * data 以对象的格式传入
 */
function getRequest(url, data) {
  var getRequest = wxPromisify(wx.request)
  return getRequest({
    url: app.globalData.url + url,
    method: ‘GET‘,
    data: data,
    header: {
      ‘Content-Type‘: ‘application/json‘
    }
  })
}

/**
 * 微信请求post方法封装
 * url
 * data 以对象的格式传入
 */
function postRequest(url, data) {
  var postRequest = wxPromisify(wx.request)
  return postRequest({
    url: app.globalData.url + url,
    method: ‘POST‘,
    data: data,
    header: {
      "content-type": "application/x-www-form-urlencoded"
    },
  })
}

//跳转到加载页面
function jumpLoading() {
  wx.redirectTo({
    url: ‘/pages/loading/index‘,
  });
}


//封装小程序冷更新
function upDateSmallProgram() {
  wx.getSystemInfo({
    success: function (res) {
      var version = res.SDKVersion.slice(0, 5);
      console.log(‘res.SDKVersion‘, res.SDKVersion)
      version = version.replace(/\./g, "");
      if (parseInt(version) >= 199) {// 大于1.9.90的版本
        const updateManager = wx.getUpdateManager()

        updateManager.onCheckForUpdate(function (res) {
          // 请求完新版本信息的回调
          console.log("9999999", res.hasUpdate)
        })

        updateManager.onUpdateReady(function () {
          wx.showModal({
            title: ‘更新提示‘,
            showCancel: false,
            content: ‘版本已更新,请点击确定立即使用!‘,
            success: function (res) {
              if (res.confirm) {
                // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
                updateManager.applyUpdate()
              }
            }
          })

        })

        updateManager.onUpdateFailed(function () {
          // 新的版本下载失败

        })
      }
    }
  })
}

module.exports = {
  postRequest: postRequest,
  getRequest: getRequest,
  jumpLoading: jumpLoading,
  upDateSmallProgram: upDateSmallProgram
}

 

微信小程序request(promise)方法封装

标签:exp   微信小程序   ace   encode   应用   post方法   false   final   UI   

原文地址:https://www.cnblogs.com/aishangliming/p/9158784.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!