wxRequest.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. function wxPromisify(fn) {
  2. return function (obj = {}) {
  3. return new Promise((resolve, reject) => {
  4. obj.success = function (res) {
  5. //成功
  6. resolve(res)
  7. }
  8. obj.fail = function (res) {
  9. //失败
  10. reject(res)
  11. }
  12. fn(obj)
  13. })
  14. }
  15. }
  16. //无论promise对象最后状态如何都会执行
  17. Promise.prototype.finally = function (callback) {
  18. let P = this.constructor;
  19. return this.then(
  20. value => P.resolve(callback()).then(() => value),
  21. reason => P.resolve(callback()).then(() => { throw reason })
  22. );
  23. };
  24. /**
  25. * 微信请求get方法
  26. * url
  27. * data 以对象的格式传入
  28. */
  29. function getRequest(url, data) {
  30. var getRequest = wxPromisify(wx.request)
  31. return getRequest({
  32. url: url,
  33. method: 'GET',
  34. data: data,
  35. header: {
  36. 'Content-Type': 'application/json'
  37. }
  38. })
  39. }
  40. /**
  41. * 微信请求post方法封装
  42. * url
  43. * data 以对象的格式传入
  44. */
  45. function postRequest(url, data) {
  46. var postRequest = wxPromisify(wx.request)
  47. return postRequest({
  48. url: url,
  49. method: 'POST',
  50. data: data,
  51. header: {
  52. "content-type": "application/json"
  53. },
  54. })
  55. }
  56. module.exports = {
  57. postRequest: postRequest,
  58. getRequest: getRequest
  59. }