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);
  });
});
1

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.