Skip to content Skip to sidebar Skip to footer

How To Limit Axios From Making More Than 2 Requests To The Same Resource At The Same Time

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.

Solution 1:

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)
})

Check this link : https://medium.com/@matthew_1129/axios-js-maximum-concurrent-requests-b15045eb69d0


Post a Comment for "How To Limit Axios From Making More Than 2 Requests To The Same Resource At The Same Time"