Limit parallel requests in Axios
npm install @cajax/axios-parallel-limitA lightweight Axios wrapper that limits the number of parallel requests using p-limit. This library allows you to control the concurrency of your HTTP requests, ensuring that your application doesn't overwhelm the server or the client.
``bash`
npm install axios-parallel-limit
`typescript
import axios from 'axios';
import { axiosParallelLimit } from 'axios-parallel-limit';
// Create an Axios instance
const http = axios.create({
baseURL: 'https://api.example.com'
});
// Apply the parallel limit
axiosParallelLimit(http, {
maxRequests: 5, // Limit to 5 concurrent requests
onActiveCountChange: (active) => {
console.log(Active requests: ${active});Pending requests: ${pending}
},
onPendingCountChange: (pending) => {
console.log();
}
});
// Now use the axios instance as usual
// Only 5 requests will run in parallel, others will be queued
for (let i = 0; i < 20; i++) {
http.get(/items/${i}).then(response => {Item ${i} loaded
console.log();`
});
}
The axiosParallelLimit function takes two arguments:axiosInstance
1. : The Axios instance to wrap.options
2. : An object with the following properties:
| Option | Type | Required | Description |
|--------|------|----------|-------------|
| maxRequests | number | Yes | The maximum number of requests that can run simultaneously. |onActiveCountChange
| | (count: number) => void | No | Callback function invoked when the number of active requests changes. |onPendingCountChange
| | (count: number) => void | No | Callback function invoked when the number of pending (queued) requests changes. |
This library wraps the Axios adapter to intercept the actual request execution. It uses p-limit to manage a queue of requests. When a request is made, it is added to the queue. If the number of active requests is below maxRequests`, the request is executed immediately. Otherwise, it waits until a slot becomes available.
MIT