限制 axios 请求本身非常容易。真正令人头疼的是如何处理从无效请求返回的Promise。处理从无效 axios 请求返回的Promise时,什么被认为是理智的行为?他们应该永远待定吗?
我没有看到这个问题的完美解决方案。但后来我想到了一个有点作弊的解决方案:
如果我们不限制 axios 调用,而是限制实际的 XMLHttpRequest 会怎样?
这让事情变得更容易,因为它避免了Promise问题,而且更容易实现。这个想法是为最近的请求实现缓存,如果新请求与最近的请求匹配,您只需从缓存中提取结果并跳过 XMLHttpRequest。
由于axios 拦截器的工作方式,以下代码段可用于有条件地跳过某个 XHR 调用:
// This should be the *last* request interceptor to add
axios.interceptors.request.use(function (config) {
/* check the cache, if hit, then intentionally throw
* this will cause the XHR call to be skipped
* but the error is still handled by response interceptor
* we can then recover from error to the cached response
**/
if (requestCache.isCached(config)) {
const skipXHRError = new Error('skip')
skipXHRError.isSkipXHR = true
skipXHRError.request = config
throw skipXHRError
} else {
/* if not cached yet
* check if request should be throttled
* then open up the cache to wait for a response
**/
if (requestCache.shouldThrottle(config)) {
requestCache.waitForResponse(config)
}
return config;
}
});
// This should be the *first* response interceptor to add
axios.interceptors.response.use(function (response) {
requestCache.setCachedResponse(response.config, response)
return response;
}, function (error) {
/* recover from error back to normality
* but this time we use an cached response result
**/
if (error.isSkipXHR) {
return requestCache.getCachedResponse(error.request)
}
return Promise.reject(error);
});