如何限制 axios 同时向同一资源发出 2 个以上的请求 [英] How to limit axios from making more than 2 requests to the same resource at the same time
本文介绍了如何限制 axios 同时向同一资源发出 2 个以上的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这就是我使用 axios 实例发出请求的方式.我需要知道对特定资源发出了多少请求,如果请求超过 2 个,我会发出通知.
This is how I am making the request using an axios instance. I need to know how many requests are made to a particular resource and if they are more than 2 I give a notification.
this.$customRequest.defaults.raxConfig = {
retry: 2,
retryDelay: 10000,
backoffType: 'static',
statusCodesToRetry: [
[100, 199],
[400, 403],
[405, 429]
],
// This happens when retry returns errors at the end
onRetryAttempt: err => {
const cfg = rax.getConfig(err);
if (cfg.currentRetryAttempt == 2) {
let informationMessage = `Cannot connect to the server.
Please reload the page. Contact the admin if this problem persists`;
this.loadToaster(informationMessage);
}
}
};
const interceptorId = rax.attach(this.$customRequest);
return new Promise((resolve) => {
this.$customRequest.get(endpoint, { params })
.then(res => {
resolve(res)
})
.catch(err => {
// Excluded status codes should load the error toaster
if (err.response.status === 404 || 500 <= err.response.status <= 599) {
let errorMessage = `The page has trouble loading. \n Try refreshing the page`;
this.loadToaster(errorMessage);
}
});
})
推荐答案
import axios from 'axios'
const MAX_REQUESTS_COUNT = 5
const INTERVAL_MS = 10
let PENDING_REQUESTS = 0
// create new axios instance
const api = axios.create({})
/**
* Axios Request Interceptor
*/
api.interceptors.request.use(function (config) {
return new Promise((resolve, reject) => {
let interval = setInterval(() => {
if (PENDING_REQUESTS < MAX_REQUESTS_COUNT) {
PENDING_REQUESTS++
clearInterval(interval)
resolve(config)
}
}, INTERVAL_MS)
})
})
/**
* Axios Response Interceptor
*/
api.interceptors.response.use(function (response) {
PENDING_REQUESTS = Math.max(0, PENDING_REQUESTS - 1)
return Promise.resolve(response)
}, function (error) {
PENDING_REQUESTS = Math.max(0, PENDING_REQUESTS - 1)
return Promise.reject(error)
})
检查此链接:https://medium.com/@matthew_1129/axios-js-maximum-concurrent-requests-b15045eb69d0
这篇关于如何限制 axios 同时向同一资源发出 2 个以上的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文