【问题标题】:Node.js: How to perform endless loop with async moduleNode.js:如何使用异步模块执行无限循环
【发布时间】:2015-05-25 21:30:11
【问题描述】:

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

有人可以帮忙吗?

提前致谢。

【问题讨论】:

    标签: node.js async.js


    【解决方案1】:

    查看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 有什么区别?在这种情况下有什么优势?
    • 这确实使用了 setTimeout。 @YlinaGreed 是对的,这可以使用递归来完成。这个例子展示了如何使用 async.js 来做同样的事情
    【解决方案2】:

    为什么只使用这样的模块来做这件事?你为什么不直接使用 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);
            });
        } 
    }
    

    这段代码不能真正用于请求并保存部分,它只是为了举例说明我的提议。

    【讨论】:

    猜你喜欢
    • 2023-04-05
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    相关资源
    最近更新 更多