上次我们说到了登录js实话的具体实现,其中用到了wx.request的访问,这里我们说下前面用到md5.js和util.js,其中md5.js这里不做说明,懂得都在这是js密码加密。这里我们重点说下用到的util.js.在这个js里面我们用Promise封装了wx.request().
具体试下代码:

var app = getApp(),

  servser = app.serData.url

//封装异步api
const 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
    })

  );
};

function repost(url,data,method,){
	this.post(url,data,method,"")
}

//封装异步requet
function post(url, data, method,message) {

  var cookie = app.serData.cookie,

    promise = new Promise(function(resolve, reject) {
		
	if(message!=""){
		wx.showLoading({
			title:message
		})
	}	

      wx.request({

        url: servser + url,

        data: data,

        method: method,

        header: {

          "Content-Type": "application/x-www-form-urlencoded",

          'Cookie': cookie

        },

        success: function(result) {

          var status = result.statusCode;

          console.log(status)
          //程序异常
          if (status != 200) {
            //系统未知异常
            wx.showToast({

              title: '服务器忙,请稍后重试!',

              icon: 'none',

            })
            return
          }

          resolve(result);
        },
        fail: function(err) {

          wx.showToast({

            title: '请求失败',

            icon: 'none',

          })
        },

      })
    })
  return promise
}

module.exports = {
  sendRequest: post,
}
正文到此结束

留言

0条评论

LEAVE A REPLY

  • face face face face face face face face face face face face face face face face face face face face face face face face face