js.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. //引入Promise
  2. var Promise = require('./es6-promise.auto.js');
  3. var token = wx.getStorageSync('token')
  4. function wxPromisify(fn) {
  5. return function (obj = {}) {
  6. return new Promise((resolve, reject) => {
  7. obj.success = function (res) {
  8. //成功
  9. resolve(res)
  10. }
  11. obj.fail = function (res) {
  12. //失败
  13. reject(res)
  14. }
  15. fn(obj)
  16. })
  17. }
  18. }
  19. //无论promise对象最后状态如何都会执行
  20. Promise.prototype.finally = function (callback) {
  21. let P = this.constructor;
  22. return this.then(
  23. value => P.resolve(callback()).then(() => value),
  24. reason => P.resolve(callback()).then(() => { throw reason })
  25. );
  26. };
  27. /** get请求方法 **/
  28. function syncGet(url, data) {
  29. var syncGet = wxPromisify(wx.request)
  30. return syncGet({
  31. url: url,
  32. method: 'GET',
  33. data: data,
  34. header: { 'Content-Type': 'application/json' }
  35. })
  36. }
  37. /** post请求方法封装 **/
  38. function syncPost(url, data) {
  39. var syncPost = wxPromisify(wx.request)
  40. return syncPost({
  41. url: url,
  42. method: 'POST',
  43. data: data,
  44. header: { "content-type": "application/x-www-form-urlencoded", 'token': token},
  45. })
  46. }
  47. //用户登录
  48. function login() {
  49. return new Promise((resolve, reject) => wx.login({
  50. success: resolve,
  51. fail: reject
  52. }))
  53. }
  54. //获取用户信息
  55. function getUserInfo() {
  56. return new Promise((resolve, reject) => wx.getUserInfo({
  57. success: resolve,
  58. fail: reject
  59. }))
  60. }
  61. //获取用户当前经纬度
  62. function getLocation(){
  63. var getLocation = wxPromisify(wx.getLocation)
  64. return getLocation({
  65. type: 'gcj02',
  66. })
  67. }
  68. //获取当前地图的缩放值
  69. function getScale(){
  70. return getScale = new Promise(function (resolve, reject) {
  71. //做一些异步操作
  72. var mapCtx = wx.createMapContext("map");
  73. mapCtx.getScale({
  74. type: 'gcj02',
  75. success: resolve,
  76. fail: reject
  77. })
  78. });
  79. }
  80. //获取当前地图的缩放值
  81. function getScale() {
  82. return getScale = new Promise(function (resolve, reject) {
  83. //做一些异步操作
  84. var mapCtx = wx.createMapContext("map");
  85. mapCtx.getScale({
  86. type: 'gcj02',
  87. success: resolve,
  88. fail: reject
  89. })
  90. });
  91. }
  92. module.exports = {
  93. syncPost: syncPost,
  94. syncGet: syncGet,
  95. login: login,
  96. getUserInfo: getUserInfo,
  97. getLocation: getLocation,
  98. getScale: getScale,
  99. }