详解微信小程序 同步异步解决办法
2017-06-23 11:33
751 查看
详解微信小程序 同步异步解决办法
小程序中函数体还没有完成,下一个函数就开始执行了,而且两个函数之间需要传参。那是因为微信小程序函数是异步执行的。但微信小程序增加了ES6的promise特性支持,微信小程序新版本中移除了promise的支持,需要自己使用第三方库来自行实现ES6的promise特性。
WxService.js
import Tools from 'Tools' import es6 from '../assets/plugins/es6-promise' class Service { constructor() { this.__init() } /** * __init */ __init() { this.tools = new Tools this.__initDefaults() this.__initMethods() } /** * __initDefaults */ __initDefaults() { // 缓存非异步方法 this.noPromiseMethods = [ 'stopRecord', 'pauseVoice', 'stopVoice', 'pauseBackgroundAudio', 'stopBackgroundAudio', 'showNavigationBarLoading', 'hideNavigationBarLoading', 'createAnimation', 'createContext', 'hideKeyboard', 'stopPullDownRefresh', ] // 缓存wx接口方法名 this.instanceSource = { method: Object.keys(wx) } } /** * 遍历wx方法对象,判断是否为异步方法,是则构造promise */ __initMethods() { for (let key in this.instanceSource) { this.instanceSource[key].forEach((method, index) => { this[method] = (...args) => { // 判断是否为非异步方法或以 wx.on 开头,或以 Sync 结尾的方法 if (this.noPromiseMethods.indexOf(method) !== -1 || method.substr(0, 2) === 'on' || /\w+Sync$/.test(method)) { return wx[method](...args) } return this.__defaultRequest(method, ...args) } }) } /** * 保留当前页面,跳转到应用内的某个页面 * @param {String} url 路径 * @param {Object} params 参数 */ this.navigateTo = (url, params) => { const $$url = this.tools.buildUrl(url, params) return new es6.Promise((resolve, reject) => { wx.navigateTo({ url: $$url, success: res => resolve(res), fail: res => reject(res), }) }) } /** * 关闭当前页面,跳转到应用内的某个页面 * @param {String} url 路径 * @param {Object} params 参数 */ this.redirectTo = (url, params) => { const $$url = this.tools.buildUrl(url, params) return new es6.Promise((resolve, reject) => { wx.redirectTo({ url: $$url, success: res => resolve(res), fail: res => reject(res), }) }) } } /** * 以wx下API作为底层方法 * @param {String} method 方法名 * @param {Object} obj 接收参数 */ __defaultRequest(method = '', obj = {}) { return new es6.Promise((resolve, reject) => { obj.success = (res) => resolve(res) obj.fail = (res) => reject(res) wx[method](obj) }) } } export default Service
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
您可能感兴趣的文章:
相关文章推荐
- 微信开发之小程序合法域名校验出错详解及解决办法
- 微信小程序 缓存(本地缓存、异步缓存、同步缓存)详解
- 微信小程序 合法域名校验出错详解及解决办法
- AJAX是什么? AJAX的交互模型(流程)?同步和异步的区别? AJAX跨域的解决办法?
- 微信小程序 出现47001 data format error原因解决办法
- 微信小程序的同步异步解决方案
- 微信小程序开发过程中tabbar页面显示的相关问题及解决办法
- AJAX是什么? AJAX的交互模型(流程)?同步和异步的区别? AJAX跨域的解决办法?
- 不在以下合法域名列表中,微信小程序解决办法
- 微信小程序开发过程中tabbar页面显示的相关问题及解决办法
- 微信小程序picker组件不能使用对象的解决办法
- AJAX是什么? AJAX的交互模型(流程)?同步和异步的区别? AJAX跨域的解决办法?
- 微信小程序-双击长按触发longtap事件时同时触发tap事件解决办法
- ajax异步模式下实现等待loading(jQuery同步Ajax带来的UI线程阻塞问题及解决办法)
- 微信小程序-双击长按longtap事件与tap事件冲突的解决办法
- AJAX是什么? AJAX的交互模型(流程)?同步和异步的区别? AJAX跨域的解决办法?
- 微信小程序 wx.uploadFile无法上传解决办法
- [转]IOS程序之HTTP同步请求与异步请求问题解决
- 关于微信小程序发起的请求不能使用session的解决办法