Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Node.js: How to perform endless loop with async module?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.2k
    Comment on it

     I have a situation where I want to run an endless loop and I have to get data from there. For this, I have to make a Http call and then put the http response in a database, In each iteration, I have to wait for some second.

    To solve this problem I am using async module.

    For this below is the code by using async.forever.

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

     


    In above code, I have used async.forever and after getting a response we will store data in a database and perform any action which we want to perform.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: