T. Cali
T. Cali

Reputation: 23

node.js Iterate through an array in intervall for certain times

I've been working on node.js for a short time and currently have the following problem: I would like to iterate through an array and send an http request for each element in the array. These requests should be executed every 5 seconds. In addition to this, this should be done max. 10 times.

That means every 5 seconds an http request should be sent for all elements in the array.

I have already tried a branched async for and for each loop, but I am not getting the desired result.

I know where the problem is with my code but can't find another solution.

It looks something like this:

// Set for loop
for (var i = 0; i <= 10; i++) {
   setTimeout(function () {
   // Iterate through every element within the array
   sendItems.forEach(function (arrayItem) {
   // Some code
   request (.....)

   // Exit condition
   if (sendItems[sendItems.length - 1].status === 'Failed'|||
      sendItems[sendItems.length - 1].status ==='Successful') {
        if (cbFlag === false) {
           interval = 0;
            resolve(sendItems);
          }
     }
   });
}interval * i);

Upvotes: 2

Views: 395

Answers (1)

alfredopacino
alfredopacino

Reputation: 3241

Assuming by request you're referring to the nodejs module. Here a possible solution using something strange like a sleep :)

const request = require('request');
const _request = require('util').promisify(request);
let sendItems = [1,2,3];

let sleep = (ms) => {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                console.log(`waiting ${ms/1000} sec..`)
                resolve();
            }, ms);
        })
}   
(async function loop() {
    for (let i = 0; i < 10; i++) {

        for (let id of sendItems) {
            let r = await  _request('https://jsonplaceholder.typicode.com/posts/'+id, { json: true })
            console.log(r.body.id);
        }
        await sleep(5000);
    } console.log("ok that's it")
})();

Upvotes: 1

Related Questions