【问题标题】:How to break out of the for loop in nodejs如何在nodejs中跳出for循环
【发布时间】:2014-04-09 04:44:47
【问题描述】:

问题很简单,我在 for 循环中使用了一个查询,如果我得到的计数小于 15,我想退出 for 循环,否则增加分配的值。但是我无法使用 break 语句,即使在第一次回调之后,循环也会继续执行。

  for (var i = 0; i < test; i++) {

                var sql = "SELECT count(*) as count FROM `tb_members` WHERE `assigned`=?";
                connection.query(sql, [assigned], function (err, response) {

                    if (response[0].count < 15) {

                        callback(assigned);

                    }
                    else {
                        ++assigned;

                        if (i == test - 1) {
                            callback(0);
                        }
                    }
                });
            }

【问题讨论】:

    标签: node.js


    【解决方案1】:

    按照您的代码编写方式,您的所有 SQL 查询都将立即开始。然后,一段时间后,查询将开始返回结果。因此,您无法跳出 @9​​87654321@ 循环,因为它已经完成并且所有 SQL 查询都已发送。

    如果您想根据前一个结果来决定是否发送下一个查询,那么您一次只能发送一个,并且由于结果的异步性质,您不能使用for循环。

    一次发送一个查询然后决定是否发送下一个查询的一种方法是:

    function sendQueries() {
        var i = 0;
    
        function next() {
            if (i < test) {
                var sql = "SELECT count(*) as count FROM `tb_members` WHERE `assigned`=?";
                connection.query(sql, [assigned], function (err, response) {
                    i++;
                    if (response[0].count < 15) {
                        callback(assigned);
                    } else {
                        ++assigned;
                        if (i == test - 1) {
                            callback(0);
                        }
                    }
                    // here you can decide whether you want to do the next iteration
                    // or not by either calling next() or not.
                    next();
                });
            }
        }
        next();
    }
    

    【讨论】:

      【解决方案2】:

      您应该使用 async 来编写这样的循环。如果您想要串行行为 - 您可以考虑使用 async.eachSeries,然后您可以通过调用有错误的回调函数来停止循环。此时循环将不再执行。但在错误处理程序中 - 忽略错误。

      在这里查看:https://github.com/caolan/async#collections

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-06
        相关资源
        最近更新 更多