微信小程序使用promise封装异步请求

一:开发了一段时间的微信小程序,发现里面的API都是这样的:

wx.showModal({
  title: '提示',
  content: '这是一个模态弹窗',
  success: function(res) {
    if (res.confirm) {
      console.log('用户点击确定')
    } else if (res.cancel) {
      console.log('用户点击取消')
    }
  }
})

如果代码多了逻辑多了,就会出现所谓的回调地狱。

wx.showModal({
  title: '提示',
  content: '这是一个模态弹窗',
  success: function(res) {
    if (res.confirm) {
      wx.showModal({
          title: '提示',
          content: '这是一个模态弹窗',
          success: function(res) {
          if (res.confirm) {
              console.log('用户点击确定')
         } 
      }
    })
    }
  }
})                  

二:ES6的promise

下面使用新学习的promise来封装微信小程序的回调API,使代码变得更优雅,易于维护。

util.js文件:

//添加finally:因为还有一个参数里面还有一个complete方法。

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 })

);

};


//封装异步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) }) } } const getLocationPromisified = wxPromisify(wx.getLocation);//获取经纬度 const showModalPromisified = wxPromisify(wx.showModal);//弹窗 // 封装post请求 const post = (url,data) => { var promise = new Promise((resolve, reject) => { //网络请求 wx.request({ url: url, data: data, method: 'POST', header: { 'content-type': 'application/x-www-form-urlencoded', 'token':wx.getStorageSync('token') }, success: function (res) {//服务器返回数据 if (res.statusCode == 200) { resolve(res); } else {//返回错误提示信息 reject(res.data); } }, error: function (e) { reject('网络出错'); } }) }); return promise; } // 封装get请求 const get = (url, data) => { var promise = new Promise((resolve, reject) => { //网络请求 wx.request({ url: url, data: data, header: { 'content-type': 'application/json', 'token': wx.getStorageSync('token') }, success: function (res) {//服务器返回数据 if (res.statusCode == 200) { resolve(res); } else {//返回错误提示信息 reject(res.data); } }, error: function (e) { reject('网络出错'); } }) }); return promise; } module.exports = { post, get, getLocationPromisified, showModalPromisified }

在index引用之后就能避免回调地狱了。

//index.js
//获取应用实例
const app = getApp()
const util = require('../../utils/util')
Page({
  data: {
    
  },
  onLoad(){
    util.showModalPromisified({
      title: '提示',
      content: '这是一个模态弹窗',
    }).then(function(res){
      console.log(res);
      if (res.confirm){
        return util.getLocationPromisified({
          type: 'wgs84'
        })
      }
    }).then(function(res){
      console.log(res)
      return util.get('https://easy-mock.com/mock/59b6617ae0dc663341a5dea4/itaem/123',{})
    }).then(function(res){
      console.log(res)
    }).catch(function(res){
      console.log(res)    
    })
  }
})

参考:https://www.jianshu.com/p/e92c7495da76