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

筅森魡賤 提交于 2019-12-11 02:35:11

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/29200981/node-js-how-to-perform-endless-loop-with-async-module

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!