微信小程序Promise 封装api 用 Proxy方法

233 阅读1分钟
// proxy 实现封装wx的所有api

let nullFn = () => {
};
console.log(wx);

function IllegalAPIException(name) {
  this.message = "No Such API [" + name + "]";
  this.name = 'IllegalAPIException';
}
let services = {
  sleep: (time) => {
    return new Promise(function (resolve, reject) {
      setTimeout(resolve, time);
    })
  },
  stop: () => {
    return new Promise(function (resolve, reject) {
    })
  },
  taskSequence: () => {
    return new Promise(function (resolve, reject) {
      resolve()
    })
  }
};


export let wsAPI = new Proxy(services, {
  get: function (target, property) {
    console.log(property,target);
    if (property in target) {
      return target[property];
    } else if (property in wx) {
      return (obj) => {
        return new Promise(function (resolve, reject) {
          obj = obj || {};
          obj.success = (...args) => {
            resolve(...args)
          };
          obj.fail = (...args) => {
            reject(...args);
          };
          obj.complete = nullFn;
          wx[property](obj);
        });
      }
    } else {
      throw new IllegalAPIException(property);
    }

  }
});
import {wsAPI} from "../../utils/wxApi"


// module.exports 导出的 
// 这样暴露出去就要被这样引用
// const wsAPI = require("../../utils/wsAPI.js")


示例:
wsAPI.taskSequence()
    .then(() => wsAPI.showLoading({title: "保存中"}))
    .then(() => wsAPI.sleep(1000))
    .then(() => wsAPI.hideLoading())
    .then(() => wsAPI.sleep(500))
    .then(() => wsAPI.showLoading({title: "载入中"}))
    .then(() => wsAPI.sleep(1000))
    .then(() => wsAPI.hideLoading())
    .then(() => console.log("done"))

注: (A)=>{B} 是 ES6 的箭头函数,相当于 function(A){B},箭头函数不用显式 return。 wsAPI 用 Proxy(ECMAScript 6 入门 / Proxy)重新封装了 wx 的所有API。并新增了 sleep ,stop 和 taskSequence。sleep 用于阻塞一段时间;taskSequence 是一个空的 Promise,让代码看起来更整齐美观,可读性更好(样例四);stop 用于停止任务序列进行下去

转载自:my.oschina.net/u/3396785/b…