1

I have used two return statements inside the function mentioned below. But still function loops for all the users.

module.exports.getByKey = function(key, callback) {
    User.find().populate('licences').exec(function(err, users) {
        if(err) {
            return callback(err);
        }
        var keyFound = false;
        users.forEach(function(user) {
            console.log("user found " + user.name);
            user.licences.forEach(function(licence) {
                console.log("licence found");
                if(licence.key == key) {
                    keyFound = true;
                    callback(null, user);
                    return;
                }
            }, this);
            if(keyFound) {
                console.log("+++++++++++++++++++++++");
                return;
            }
        }, this);
        // return callback({error: "Invalid Key"});
    });
}
Vishal
  • 6,238
  • 10
  • 82
  • 158
  • `.forEach()` does not support a way to break out of the loop. Your `return` is just returning from the `.forEach()` callback, not from the parent function. If you want to break out, then use a traditional `for' loop where you can then use `break` or `return` or in ES6, use a `for/of` loop. – jfriend00 Sep 22 '17 at 22:03

2 Answers2

4

Array#forEach iterates all elements of an array, it does not respect any return value.

To use a short circuit, you could use Array#some and return true for stopping iteration or Array#every, here you need to return a truthy value for continuing the looping.

By using a nested approach you need to bubble the return value to the outer array loop.

var keyFound = users.some(function(user) {            // return some
        return user.licences.some(function(licence) { // return some
            if (licence.key == key) {
                callback(null, user);
                return true;
            }
        }, this);
    }, this);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Because return the inner anonymous function; the same function is called again for the following user (external foreach)

ivan.rosina
  • 368
  • 3
  • 9