wxRequest.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import './wxPromise.js'; // loading配置,请求次数统计
  2. function startLoading() {
  3. uni.showLoading({
  4. title: '',
  5. mask: true
  6. });
  7. }
  8. function endLoading() {
  9. uni.hideLoading();
  10. }
  11. function showFullScreenLoading() {
  12. if (getApp().globalData.loadingCount == 0) {
  13. startLoading();
  14. }
  15. getApp().globalData.loadingCount++;
  16. }
  17. function tryHideFullScreenLoading() {
  18. if (getApp().globalData.loadingCount <= 0) {
  19. return;
  20. }
  21. getApp().globalData.loadingCount--;
  22. if (getApp().globalData.loadingCount == 0) {
  23. // console.log('结束..')
  24. endLoading();
  25. }
  26. } // 请求
  27. function wxRequest(url, type, data, nextInvoke) {
  28. var res = {};
  29. return new Promise(function (resolve, reject) {
  30. data.token = getApp().globalData.token;
  31. realRequest(url, type, data, nextInvoke).then(
  32. (res) => {
  33. // console.log(res);
  34. resolve(res);
  35. },
  36. (e) => {
  37. reject(e);
  38. }
  39. );
  40. });
  41. }
  42. function realRequest(url, type, data, nextInvoke) {
  43. showFullScreenLoading();
  44. if (nextInvoke) {
  45. getApp().globalData.loadingCount = 2;
  46. } // console.log('loadingCount',getApp().globalData.loadingCount)
  47. return new Promise(function (resolve, reject) {
  48. uni.pro
  49. .request({
  50. url: getApp().globalData.api + url,
  51. method: type,
  52. data: data
  53. })
  54. .then((res) => {
  55. tryHideFullScreenLoading();
  56. var res = res.data; // console.log(res);
  57. if (res.code == 200) {
  58. // console.log(res.result)
  59. resolve(res);
  60. } // 逻辑报错
  61. else if (res.code == 204) {
  62. reject(res.msg);
  63. } // token失效
  64. else if (res.code == 401) {
  65. getApp().globalData.userInfo = null;
  66. getApp().globalData.token = null; // token报错,跳转到登录页面
  67. uni.pro.redirectTo({
  68. url: '/pages/login/index/index'
  69. });
  70. reject(res.msg);
  71. }
  72. reject(res.msg);
  73. })
  74. .catch((err) => {
  75. // 接口连续调用时报错,需主动关闭
  76. if (nextInvoke) {
  77. getApp().globalData.loadingCount = 1;
  78. tryHideFullScreenLoading();
  79. } else {
  80. // 正常 非连续调用
  81. tryHideFullScreenLoading();
  82. }
  83. console.log(err);
  84. reject('网络异常,请稍后再试');
  85. });
  86. });
  87. }
  88. exports.wxRequest = wxRequest;