uniapp uni.request重复请求处理
类似这种切换tab时,如果操作很快并且网络不太好,就出现数据错乱,在网上查了一圈,有一个使用uview拦截处理的,但是原生uni.requse没有找到详细的解决办法,就查到使用 abort 方法,我自己封装了一个,试了一下效果还可以。
request.js
const pending = []; // 用来记录队列中的请求
// 判断是否有重复的请求并移除
let removePending = (config) => {
for (let p = 0; p < pending.length; p++) {
console.log(pending[p]);
if (pending[p].u === config.url?.split("?")[0] + "&" + config.method) {
//当当前请求在数组中存在时执行函数体
pending[p].requestTask.abort();
pending.splice(p, 1); //数组移除当前请求
}
}
};
export function request(options) {
return new Promise((reslove, reject) => {
// 每次发送请求之前判断一下
removePending(options);
const requestTask = uni.request({
...,
complete: (res) => {
// 从请求队列中移除已经执行完成的请求
const excutingIndex = pending.findIndex(item => item.requestTask === requestTask)
pending.splice(excutingIndex, 1)
}
})
//把请求加入队列数组中
pending.push({
u: options.url?.split("?")[0] + "&" + options.method,
requestTask: requestTask,
});
})
}