因为uni-app不彻底支持proxy,因此须要自行实现一个proxy类,代理uni的接口,将success和fail的回调转为resolve和reject.javascript
promisfy.jsjava
/* * @author: hruomei * @description: uni-app接口promise化 * @create-time: 2020/05/19 * @last-update-time: 2020//05/19 * @version: V1.0 */ let $uni; // #ifdef MP $uni = new Proxy(wx, { get: (target, key) => { return (options) => { return new Promise((resolve, reject) => { target[key]({ ...options, success: resolve, fail: reject }); }) } }, set: (target, key, value) => { target[key] = value; } }) // #endif // #ifndef MP $uni = new Proxy(uni, { get: (target, key) => { return (options) => { return new Promise((resolve, reject) => { target[key]({ ...options, success: resolve, fail: reject }); }) } }, set: (target, key, value) => { target[key] = value; } }); // #endif export default $uni;
在main.js中 小程序
import $uni from './commons/promisfy.js' Vue.prototype.$uni = $uni
使用方式promise
this.$uni.getSystemInfo().then(res => {}).catch(e =>{})
以上方案若是测试有效,后面的内容就不须要看了(本人使用HbuilderX2.6.0以上版本测试H五、APP、小程序三端有效)app
存在的隐患测试
uni-app官方文档中说明,IOS8/IOS9/Android设备不支持Proxy(可是我测了是能够用),因此咱们能够参考一下方案,模拟Proxy,实现代理ui
**这里只是一个小练习,H5端能够用,但在其余端uni对象被代理不能直接访问,因此在在H5端用着玩玩就好this
promisfy.jsprototype
function isObject(target) { return typeof(target) === 'object' || target === null; } function clone(target) { if (!isObject(target)) return target; let newTarget = new Object(); for (let i in target) { newTarget[i] = clone(target[i]); } return newTarget; } // 由于uni的API只有一个层级,因此这里只代理了1个层级的API,UniProxy只针对uni-app function UniProxy(target, handle) { if (!isObject(target)) throw new Error('UniProxy(): variable "target" must be an object'); let targetCopy = clone(target); Object.keys(targetCopy).forEach((key) => { Object.defineProperty(targetCopy, key, { get: () => { return handle.get && handle.get(target, key); }, set: (newVal) => { handle.set && handle.set(target, key, newVal); } }); }); return targetCopy; } const $uni = new UniProxy(uni, { get: (target, key) => { return (options) => { return new Promise((resolve, reject) => { target[key]({ ...options, success: resolve, fail: reject }); }) } }, set: (target, key, value) => { target[key] = value; } }); export default $uni;
在main.js中 代理
import $uni from './commons/promisfy.js' Vue.prototype.$uni = $uni
使用方式
this.$uni.getSystemInfo().then(res => {}).catch(e =>{})