wxRequest.js 2.4 KB

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