To limit the number of simultaneous requests that are in flight at a time, I would recommend using Bluebird Promise.map() , which offers the concurrency option. He will do all of the following for you:
- Iterate your array
- Limit the number of simultaneous requests to what you set for the concurrency parameter so that
- Collect all the results in order in an array of final results
Here's how you use it:
const Promise = require('bluebird'); Promise.map(records, r => { let placeName = r['Place Name']; return geocoder.geocodeAsync(placeName)); }, {concurrency: 5}).then(results => {
Note. The speed limit is usually independent of the number of simultaneous requests. Limiting the number of simultaneous requests will lead to a greater likelihood that you will remain under the rate limit, but do not guarantee it. There are special speed limit modules that can directly control the speed limit.
You can add a delay to each request using Bluebird .delay() .
const Promise = require('bluebird'); Promise.map(records, r => { let placeName = r['Place Name']; return geocoder.geocodeAsync(placeName)).delay(500); }, {concurrency: 5}).then(results => {
The classic algorithm for dealing with some types of speed limits is called the leaky bucket algorithm .
If your limit is 50 requests / sec, you can just make sure your concurrency number multiplies the delay time by more than 50 / sec.
source share