如何突破Node.js中的for循环

Pan*_*dal 2 node.js

好了,问题很简单,我在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);
                        }
                    }
                });
            }
Run Code Online (Sandbox Code Playgroud)

jfr*_*d00 5

编写代码的方式,所有SQL查询将立即开始。然后,稍后,查询将开始返回结果。因此,您无法打破for循环,因为它已经完成并且所有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();
}
Run Code Online (Sandbox Code Playgroud)