如何在函数内部中断for循环? (的node.js)

时间:2017-02-03 06:39:45

标签: javascript

我正在使用此库:https://github.com/NodeRedis/node_redis

以下是我的代码示例:

var redis = require('redis');
var redisdb = redis.createClient(); //creates a new client
var multi = redisdb.multi();

redisdb.on('connect', function() {
    console.log('connected to redis');
});

redisdb.flushdb(function(err, success) {
    if (success) {
        console.log('cleared redis DB');
    }
});

redisdb.sadd("list", "list:1");
redisdb.sadd("list:1", "list:1:stuff:abc");
redisdb.sadd("list", "list:2");
redisdb.sadd("list", "list:3");
redisdb.sadd("list:3", "list:3:stuff:def");
redisdb.sadd("list", "list:4");
redisdb.sadd("list", "list:5");
redisdb.sadd("list", "list:6");
redisdb.sadd("list", "list:7");
redisdb.sadd("list", "list:8");
redisdb.sadd("list", "list:9");
redisdb.sadd("list", "list:10");
redisdb.sadd("list", "list:11");
redisdb.sadd("list", "list:12");
redisdb.sadd("list", "list:13");
redisdb.sadd("list", "list:14");
redisdb.sadd("list", "list:15");

var abc = function(value) {
    console.log(value);
    /*
    returns:
    [ 'list:3' ]
    [ 'list:1' ]
*/
}

redisdb.smembers('list', function(err, mems) {
            if (mems && mems.length > 0) {
                for (var i = 0; i < mems.length; i++) {
                    redisdb.scard(mems[i], function(err, data) {
                        if (data > 0) {
                        abc(this.args); //would like it if the loop stopped here
                    }
                    });
                }
            }
            });

我希望循环从我调用函数abc的那一刻开始停止。因此,在这种情况下,它只会返回[ 'list:3' ]

我怎么能这样做?

由于

3 个答案:

答案 0 :(得分:0)

只需在abc通话后添加一个休息时间:

if (data > 0) {
  abc(this.args)
  break
}

break将退出循环。

答案 1 :(得分:0)

if (data > 0) {
                    abc(this.args); //would like it if the loop stopped here
                    return;  
                }

or 

 if (data > 0) {
                    abc(this.args); //would like it if the loop stopped here
                    i= mems.length; //Not a best practice 
                }

答案 2 :(得分:0)

def func(prefix,suffixes,size):
    k = len(suffixes)
    return [prefix+str(n/k+1)+suffixes[n%k] for n in range(size*k)]

# usage example:
print func('s',['a','b'],10)

这是非常基本的算法内容,类似于所有c语法编程语言。见http://www.w3schools.com/js/js_loop_for.asp