4

I am creating an app in NodeJS just to send JSON documents to a distant API.

My problem is that my JSON is big, and Node tries to send as fast as possible items from the array, which is way too fast for the API.

How could I slow down a little bit the forEach function ? I really can't find where to put a setTimeout somewhere, Node is always going on with the next step...

I show you my code, I'm pretty sure is not that hard, but it feels like this exactly what NodeJs is not really made for, is it ?

var datajson = "MY JSON";

datajson.forEach(function (element) {

  var options = {
    method: 'POST',
    url: 'http://XXX',
    headers: { XXX },
    body: { XXX },
    json: true
  };

  request(options, function (error, response, body) {
    if (error) throw new Error(error);
    console.log(body);
  });
});
Patrick Hund
  • 19,163
  • 11
  • 66
  • 95
Mugwortt
  • 53
  • 5

1 Answers1

3

You could use setInterval to periodically invoke a function that sends the post requests, like this:

var datajson = "MY JSON1";

var delay = 1000;

var index = 0;

var interval = setInterval(function () {
  var element = datajson[index];

  var options = {
    method: 'POST',
    url: 'http://XXX',
    headers: { XXX },
    body: { XXX },
    json: true
  };

  request(options, function (error, response, body) {
    if (error) {
      clearInterval(interval);
      throw new Error(error);
    }
    console.log(body);
  });

  // stop sending post requests when all elements have been sent
  if (++index === datajson.length) {
    clearInterval(interval);
  }
}, delay)
Patrick Hund
  • 19,163
  • 11
  • 66
  • 95