I'm writing a NodeJS script that calls a bunch of APIs via GET (using request
from npm) and saves the responses in a JSON file. I'm using a for
to loop through IDs to pass to the APIs, but I'm having trouble putting in a delay between call bursts so I don't spam the API server and make it mad at me (rate limiting). Does anyone know how to do this?
My current code (without any delay):
var fs = require('fs');
var request = require('request');
// run through the IDs
for(var i = 1; i <= 4; i++)
{
(function(i)
{
callAPIs(i); // call our APIs
})(i);
}
function callAPIs(id)
{
// call some APIs and store the responses asynchronously, for example:
request.get("https://example.com/api/?id=" + id, (err, response, body) =>
{
if (err)
{throw err;}
fs.writeFile("./result/" + id + '/' + id + '_example.json', body, function (err)
{
if (err)
{throw err;}
});
});
}
I'm looking for this behavior:
callAPIs(1); // start a burst of calls for ID# 1
// wait a bit...
callAPIs(2); // start a burst of calls for ID# 2
// wait a bit...
// etc