Node.js: 如何使用异步模块执行死循环

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

我需要进行 HTTP 调用,然后将响应放入数据库中。我应该永远重复它。我一直在阅读异步模块,但我不明白如何将这些操作与每次迭代之间的几秒钟等待结合起来。

有人可以帮忙吗?

提前致谢。

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

为什么只使用这样的模块来做这个?你为什么不像这样使用 setTimeout:

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

当然,这段代码不会真正用于请求和保存部分,它只是为了举例说明我的建议。