微信小程序使用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

 

转载于:https://www.cnblogs.com/weihuan/p/9113944.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值