| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- import common from "@/utils/common";
- // 用于存储每个请求接口的请求任务
- const requestTasks = {};
- /**
- * 封装的请求函数
- * @param {Object} options - 请求配置对象
- * @param {string} options.url - 请求的接口地址
- * @param {string} [options.method='POST'] - 请求方法,默认为 POST
- * @param {Object} [options.data={}] - 请求数据,默认为空对象
- * @param {Function} [options.success] - 请求成功的回调函数
- * @param {Function} [options.fail] - 请求失败的回调函数
- */
- function requestWithCancel(options) {
- const { url, method = 'POST', data = {} } = options;
- // 检查该接口是否有正在进行的请求
- if (requestTasks[url]) {
- // 取消上一次的请求
- requestTasks[url].abort();
- // 清除存储的请求任务
- delete requestTasks[url];
- }
- return new Promise((resolve, reject) => {
- // 发起新的请求并保存请求任务
- const requestTask = wx.request({
- url,
- method,
- data: {
- data: common.desEncrypt(JSON.stringify(data), getApp().globalData.apiSecretKey),
- },
- header: {
- 'content-type': 'application/json',
- token: wx.getStorageSync('token'),
- appId: "KASIET_alismaillpro",
- },
- success: async (res) => {
- // await sleep(Math.random() * 1000); // 竞争测试
- // 请求成功时清除存储的请求任务
- delete requestTasks[url];
- // 前端判断返回的参数是不是加密数据,是的话先解密
- if ((typeof res.data.data == 'string') && res.data.data.constructor == String) {
- res.data = JSON.parse(common.desDecrypt(res.data.data, getApp().globalData.apiSecretKey));
- }
- resolve(res);
- },
- fail: (err) => {
- // 请求失败时清除存储的请求任务
- delete requestTasks[url];
- reject(err);
- },
- complete: (res) => {
- // 请求完成时清除存储的请求任务
- delete requestTasks[url];
- console.log(res);
- }
- });
- // 存储当前请求的任务
- requestTasks[url] = requestTask;
- })
- }
- const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
- module.exports = {
- requestWithCancel
- };
|