user9667412
user9667412

Reputation:

How to make api requests with a timer in node js?

I have an array which contains some data and for each data item an api request has to be made. The api will remain same but the array index will increment every time the api request is made. Also the api request has to be called with a gap of 5 minutes. Hence I can't call the api for the entire array all at once. One api call is made with Array[0] in the request body and after 5 minutes api call is made with Array[1] in the request body. I tried to implement a cron job with these requirements but there are no proper examples for a cron job within a for loop with api calls. Any help would be appreciated. `

const array = ['http://linkedin.com/charles123', 'http://linkedin.com/darwin123' ... ]

//API needs to be called every 5 minutes
const sendConnectionRequest = () => {
var i = 0;
for(i; i< array.length, i++) {
  fetch("serverurl:123", {
    headers: {
     'Content-Type': 'application/json'
    },
    method: "POST",
    body: JSON.stringify(array[i])
  })
  .then((res) => if(res) { console.log('Connection Request Send') } )
 }
}`

Upvotes: 0

Views: 1880

Answers (3)

Dan Starns
Dan Starns

Reputation: 3825

May I suggest using an Async Generator this will allow you to manage sequential promises.

const fetch = require("node-fetch");
const sleep = require("util").promisify(setTimeout);

async function* responseGenerator(urls) {
    let iterations = 0;

    while (urls.length) {
        const [url, ...rest] = urls;

        urls = rest;

        if (iterations > 0) {
            await sleep(50000);
        }

        yield fetch("serverurl:123", {
            headers: {
                "Content-Type": "application/json"
            },
            method: "POST",
            body: JSON.stringify(url)
        });

        iterations += 1
    }
}

const array = ['http://linkedin.com/charles123', 'http://linkedin.com/darwin123' ]

for await (const response of responseGenerator(array)) {
    // response.status
    // response.statusText
    // response.contentType
}

Upvotes: 1

aatish
aatish

Reputation: 57

const array = ['http://linkedin.com/charles123', 'http://linkedin.com/darwin123' ... ]

//API needs to be called every 5 minutes
const sendConnectionRequest = (data) => {

  fetch("serverurl:123", {
    headers: {
     'Content-Type': 'application/json'
    },
    method: "POST",
    body: JSON.stringify(data)
  })
  .then((res) => if(res) { console.log('Connection Request Send') } )

}



const callApi =  setInterval(()=> {
  sendConnectionRequest(array[0])
  array.shift()
}, 30000);

Upvotes: 0

Lucino772
Lucino772

Reputation: 101

There are multiple way of doing timers in node.js. Check this link.

setInterval is a infinite loop and between each iteration it wait a certain amount of time.

Upvotes: 0

Related Questions