简体   繁体   中英

How to break out of a for loop while inside of a function? (node.js)

I'm using this library: https://github.com/NodeRedis/node_redis

Here's an example of my code:

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

I want the loop to stop from the moment that I call on the function abc . Therefore in that case it would only return [ 'list:3' ] .

How would I be able to do that?

Thanks

Just add a break in right after your abc call:

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

break will exit a loop.

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 
                }
for(var i = 0, var found = false; i < Mena.index &&  found   == false; i ++) 
{
   //your stuff...
   if(data>0) 
   {
      //your stuff...
      found = true; //break
   }
 }

This is pretty basic algorithm stuff and similar for all c syntax programing languages. See http://www.w3schools.com/js/js_loop_for.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM