在我们的日常开发当中,很多时候会出现短时间内接口重复请求的情况,假如没有妥当地解决,很可能会造成以下的影响:
各个请求受网络等因素的影响,响应返回的时间无法确定,导致响应返回顺序与请求顺序不一致,也就是竟态问题。如下图所示,期待的回调函数的执行顺序应是回调1 > 回调2 > 回调3,但实际顺序是回调2 > 回调3 > 回调1;
以肯定的频率发送请求,即在特定时间内只允许发送一次请求:
throttle(time, function() { // todo})
适用于频繁触发并且需要给予客户少量反馈的场景,如:resize、scroll、mousemove
间隔时间大于指定时间才发送请求:
debounce(time, function() { // todo})
按序请求
顾名思义,就是按照开发者期待的顺序,将各个请求存储在一个队列当中,只有当上一个请求的数据响应了,才能继续发起下一次请求。
同时存在多个请求时,只取最新请求数据
当触发新的请求时,取消正在pending中的请求,使得永远只有最新的请求可以最终生效。
方案1,2 时间间隔不好把控,并且由于会丢失掉部分请求,因而只能针对get请求;
方案3看起来最笨,等待时间长,请求未减少,但由于他将请求排成了一个队列,所以可以避免post请求导致数据数据絮乱的情况;
方案4的请求未减少,并且实际上也无法控制该请求能否已经到达服务器,但该方案保证了在前台不执行无效的响应回调;
根据项目的实际情况,我最终选择了方案4,而该方案恰好可以通过axios的 cancelToken来实现。
设置一个列表pendingList,用于存储当前处于pending的请求,在每个请求发送之前,先判断当前请求能否已经存在于pendingList中。若存在,则说明该请求已被请求过,造成了重复请求,这时候则需要把重复的请求cancel,再把新请求增加到pendingList中。若不存在,则说明这个请求是干净的,可进行正常请求,同时也需要把这个请求增加到pendingList中,在请求结束后再把该请求从pendingList中移除。
其中,我们可以通过axios cancelToken来取消请求
axios提供了两种方法来取消请求
const CancelToken = axios.CancelToken;const source = CancelToken.source();axios.get('/user/12345', { cancelToken: source.token}).catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // handle error }});axios.post('/user/12345', { name: 'new name'}, { cancelToken: source.token})// cancel the request (the message parameter is optional)source.cancel('Operation canceled by the user.');
const CancelToken = axios.CancelToken;let cancel;axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // An executor function receives a cancel function as a parameter cancel = c; })});// cancel the requestcancel();
设置一个列表pendingList,用于存储当前处于pending的请求
const pendingList = new Map();
提供getFetchKey方法,用于生成各个请求的标识,当为GET请求时,由于只用于获取数据,因而只需当method和url都一致时,我们即可以认为这是同一请求,而其余请求则还需要加上请求的参数。
const getFetchKey = (config) => { const { useCancelToken } = config; //useCancelToken 用于配置该接口能否需要检测查复请求 if (useCancelToken) { const { headers, url, data, method, params } = config; let token; if (method === 'GET') { token = [method, url].join('&'); } else { token = [method, url, JSON.stringify(data), JSON.stringify(params)].join('&'); } return token; }};
增加请求到pendingList
const addPending = (config) => { const fetchKey = getFetchKey(config); if (fetchKey) { config.cancelToken = config.cancelToken || new axios.CancelToken((cancel) => { if (!pendingList.has(fetchKey)) { pendingList.set(fetchKey, cancel); } }); }};
把请求从pendingList移除
const removePending = (config) => { const fetchKey = getFetchKey(config); if (fetchKey) { if (pendingList.has(fetchKey)) { pendingList.delete(fetchKey); } }};
把请求从pendingList移除并取消该请求
const cancelPending = (config) => { const fetchKey = getFetchKey(config); if (fetchKey) { if (pendingList.has(fetchKey)) { const cancel = pendingList.get(fetchKey); cancel(fetchKey); pendingList.delete(fetchKey); } }};
在阻拦器中增加以上方法
axios.interceptors.request.use((config) => { //发送请求前首先检查该请求能否已经重复,重复则进行取消并移除 cancelPending(config); //增加该请求到pendingList中 addPending(config); return config;});axios.interceptors.response.use((response) => { const config = response.config; //请求完成后移除该请求 removePending(config); return response;});
最后,因取消请求抛出的error我们不应该返回给客户,使用axios.isCancel()判断当前请求能否是主动取消的
axios.(options).then(...)..catch((error) => { if (axios.isCancel(error)) { console.warn('repeated request: ' + error.message); return; } reject(error); });