4

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.

2 Answers 2

8

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

2 Comments

what's the difference between this and using setTimeout? what are the advantages in this case?
This does use setTimeout. @YlinaGreed is right though, this can be done using recursion. This example shows how to do the equivalent using async.js
3

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.

2 Comments

Thanks! i have been trying to do something like this but i ran into a situation where memory got bigger and bigger for some reason ...
I would be concerned about endless recursion developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

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.