singletonRequest.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import common from "@/utils/common";
  2. // 用于存储每个请求接口的请求任务
  3. const requestTasks = {};
  4. /**
  5. * 封装的请求函数
  6. * @param {Object} options - 请求配置对象
  7. * @param {string} options.url - 请求的接口地址
  8. * @param {string} [options.method='POST'] - 请求方法,默认为 POST
  9. * @param {Object} [options.data={}] - 请求数据,默认为空对象
  10. * @param {Function} [options.success] - 请求成功的回调函数
  11. * @param {Function} [options.fail] - 请求失败的回调函数
  12. */
  13. function requestWithCancel(options) {
  14. const { url, method = 'POST', data = {} } = options;
  15. // 检查该接口是否有正在进行的请求
  16. if (requestTasks[url]) {
  17. // 取消上一次的请求
  18. requestTasks[url].abort();
  19. // 清除存储的请求任务
  20. delete requestTasks[url];
  21. }
  22. return new Promise((resolve, reject) => {
  23. // 发起新的请求并保存请求任务
  24. const requestTask = wx.request({
  25. url,
  26. method,
  27. data: {
  28. data: common.desEncrypt(JSON.stringify(data), getApp().globalData.apiSecretKey),
  29. },
  30. header: {
  31. 'content-type': 'application/json',
  32. token: wx.getStorageSync('token'),
  33. appId: "KASIET_alismaillpro",
  34. },
  35. success: async (res) => {
  36. // await sleep(Math.random() * 1000); // 竞争测试
  37. // 请求成功时清除存储的请求任务
  38. delete requestTasks[url];
  39. // 前端判断返回的参数是不是加密数据,是的话先解密
  40. if ((typeof res.data.data == 'string') && res.data.data.constructor == String) {
  41. res.data = JSON.parse(common.desDecrypt(res.data.data, getApp().globalData.apiSecretKey));
  42. }
  43. resolve(res);
  44. },
  45. fail: (err) => {
  46. // 请求失败时清除存储的请求任务
  47. delete requestTasks[url];
  48. reject(err);
  49. },
  50. complete: (res) => {
  51. // 请求完成时清除存储的请求任务
  52. delete requestTasks[url];
  53. console.log(res);
  54. }
  55. });
  56. // 存储当前请求的任务
  57. requestTasks[url] = requestTask;
  58. })
  59. }
  60. const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
  61. module.exports = {
  62. requestWithCancel
  63. };