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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM