//引入Promise var Promise = require('./es6-promise.auto.js'); var token = wx.getStorageSync('token') function wxPromisify(fn) { return function (obj = {}) { return new Promise((resolve, reject) => { obj.success = function (res) { //成功 resolve(res) } obj.fail = function (res) { //失败 reject(res) } fn(obj) }) } } //无论promise对象最后状态如何都会执行 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 }) ); }; /** get请求方法 **/ function syncGet(url, data) { var syncGet = wxPromisify(wx.request) return syncGet({ url: url, method: 'GET', data: data, header: { 'Content-Type': 'application/json' } }) } /** post请求方法封装 **/ function syncPost(url, data) { var syncPost = wxPromisify(wx.request) return syncPost({ url: url, method: 'POST', data: data, header: { "content-type": "application/x-www-form-urlencoded", 'token': token}, }) } //用户登录 function login() { return new Promise((resolve, reject) => wx.login({ success: resolve, fail: reject })) } //获取用户信息 function getUserInfo() { return new Promise((resolve, reject) => wx.getUserInfo({ success: resolve, fail: reject })) } //获取用户当前经纬度 function getLocation(){ var getLocation = wxPromisify(wx.getLocation) return getLocation({ type: 'gcj02', }) } //获取当前地图的缩放值 function getScale(){ return getScale = new Promise(function (resolve, reject) { //做一些异步操作 var mapCtx = wx.createMapContext("map"); mapCtx.getScale({ type: 'gcj02', success: resolve, fail: reject }) }); } //获取当前地图的缩放值 function getScale() { return getScale = new Promise(function (resolve, reject) { //做一些异步操作 var mapCtx = wx.createMapContext("map"); mapCtx.getScale({ type: 'gcj02', success: resolve, fail: reject }) }); } module.exports = { syncPost: syncPost, syncGet: syncGet, login: login, getUserInfo: getUserInfo, getLocation: getLocation, getScale: getScale, }