Title: Axios requests in a loop after previous completes
Tags: javascript;axios;httprequest;synchronous
Question: The application I am building involves sending video frames to the server for processing. I am using Axios to send a POST request to the server. I intend to send about 3-5 frames(POST request) per second. I need to send one after the previous request completes because the next request has data in the request body which depends on the response of the previous request.
I tried running it in a loop but that won't do because the next one starts before the previous one completed. In the current code, I have something like this -
```const fun = () =&gt; {
    axios.post(url,data)
         .then((res) =&gt; {
              // process the response and modify data accordingly
              // for the next request
          })
         .finally(() =&gt; fun());
};
```
This way I am able to achieve the requests to be one after another continuously. But I am unable to control the number of requests that are being sent per second. Is there any way I can limit the number of requests per second to be say at max 5?
Additional Info: I am using this for a web app where I need to send webcam video frames(as data URI) to the server for image processing and the result back to the client after it. I am looking to limit the number of requests to reduce the internet data consumed by my application and hence would like to send at the max 5 requests per second(preferably evenly distributed). If there's a better way that Axios POST requests for this purpose, please do suggest :)

Comment: Have you looked at Bottleneck? https://www.npmjs.com/package/bottleneck

Comment: Just my 2 cents, this sounds like a great case of using websockets, if they're supported by the backend.

Comment: @Ak47 the advantage of websockets is that you can send data back and forward without constant handshaking which is usually required for each post/get request. Once you open the websocket channel streaming the data is really straightforward and it costs less for the backend to handle websocket data than continuous post requests.

Comment: @VladimirBogomolov I know I can use websockets. Just wondering if my method has any disdavantages or flaws? I am using python and flask in the backend, so websockets is probably supported

Here is the accepted answer: An amazing library called Bottleneck can come to your aid here. You can limit the number of request per second to any number you want using the following code:
```const Bottleneck = require(&quot;bottleneck&quot;);
const axios = require('axios');
const limiter = new Bottleneck({
    maxConcurrent: 1,
    minTime: 200
});

for(let index = 0; index < 20; index++){
    limiter.schedule(() =&gt; postFrame({some: 'data'}))
        .then(result =&gt; {
            console.log('Request response:', result)
        })
        .catch(err =&gt; {
            console.log(err)
        })
}


const postFrame = data =&gt; {
    return new Promise((resolve, reject) =&gt; {
        axios.post('https://httpstat.us/200', data)
            .then(r =&gt; resolve(r.data))
            .catch(e =&gt; reject(e))
    });
}
```
By manipulating the limiter
```const limiter = new Bottleneck({
    maxConcurrent: 1,
    minTime: 200
});
```
You can get your axios request to fire at any rate with any concurrency.
For instance to limit the number of request per second to 3, you would set ```minTime``` to ```333```. Stands to reason, if you want to limit it to 5 per second, it would have to be set to ```200```.
Please refer the the Bottleneck documentation here: https://www.npmjs.com/package/bottleneck

Comment for this answer: @Ak47 Not off the top of my head. That's something I will think about, but in the meantime, let me point out that I use this exact code to post records from a file line by line using axios. I send out 4 requests per second. Some files contain literally millions of lines and this sucker works like a charm every time on pretty pedestrian hardware. So if your concern specifically is that it will end up using too much resources, I would argue you'd probably be all right. It has the nifty `limiter.stop()` function to arbitrarily kill the execution.
Comment for this answer: @Ak47 Very interesting observation. Are you running your process in a browser? I do disclaim any experience using Bottlenck in a browser as my stuff runs on a Node server.
Comment for this answer: Thanks...This looks like it will work in my case. I will try it out
Comment for this answer: I tried the library but it doesn't work for infinite loops. In my case, I have to keep the request running till client makes it stop. It seems that the library is queuing up all the request from the start itself and stopping so as to achieve minTime for each request. I think it would be demanding if I wanted to keep it running for long time since all queue gets queued from start itself. Is there a way I can just schedule 5 request per second and loop it infinitely without maintaining queue as this library seems to do?
Comment for this answer: It seems to run up to hundreds of thousands in loop but starts lagging if I increasing looping any more. It probably means it is consuming resources. Although my usecase suffices in much less number of loops but I was just wondering if there's a way to handle a case where the requests needed to be kept going indefinitely. I will look if there's a way to achieve what I described above. Thanks for the help :)
Comment for this answer: yes, I am using it in my react app in browser.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 4, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2020:00:12/17/20', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><axios><httprequest><synchronous>', 'Title': 'Axios requests in a loop after previous completes', 'ViewCount': 499, 'id': 65346687, 'user_AboutMe': '<p>I code sometimes and then I Stackoverflow sometimes...</p>\n', 'user_AccountId': 18660819.0, 'user_DisplayName': 'Abhishek Bhagate', 'user_Reputation': 5332.0, 'user_Views': 947.0, 'user_id': 13602076.0}}