Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: How to perform endless loop with async module

I need to make an HTTP call and then put the response in database. i should repeat it forever. i have been reading on async module but i didn't understood how to combine these actions along with the waiting for couple of seconds between each iteration.

Can someone help?

Thanks in advance.

like image 677
Yossi Avatar asked Dec 25 '22 21:12

Yossi


2 Answers

Why using such a module only for doing this ? Why don't you just use setTimeout like:

function makeRequest() {
    request(url, function(response) {
        saveInDatabase(function() {
            // After save is complete, use setTimeout to call again
            // "makeRequest" a few seconds later (Here 1 sec)
            setTimeout(makeRequest, 1000);
        });
    } 
}

This code won't really work for the request and save part of course, it was just to give an example of what I was proposing.

like image 31
YlinaGreed Avatar answered Jan 18 '23 20:01

YlinaGreed


Look into async.forever. Your code would look something like this:

var async = require("async");
var http = require("http");

//Delay of 5 seconds
var delay = 5000;

async.forever(

    function(next) {

        http.get({
            host: "google.com",
            path: "/"
        }, function(response) {

            // Continuously update stream with data
            var body = "";

            response.on("data", function(chunk) {
                body += chunk;
            });

            response.on("end", function() {

                //Store data in database
                console.log(body);

                //Repeat after the delay
                setTimeout(function() {
                    next();
                }, delay)
            });
        });
    },
    function(err) {
        console.error(err);
    }
);
like image 64
gregnr Avatar answered Jan 18 '23 21:01

gregnr