Skip to content

Instantly share code, notes, and snippets.

@recca0120
Forked from matthewsuan/axios.js
Created February 19, 2024 08:08
Show Gist options
  • Save recca0120/7dee14b1f8f05418ae6d50616889845a to your computer and use it in GitHub Desktop.
Save recca0120/7dee14b1f8f05418ae6d50616889845a to your computer and use it in GitHub Desktop.
Axios request queue-like that limits number of requests at any given time
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)
})
export default api
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment