Ariel Weinberger
Ariel Weinberger

Reputation: 2291

Returning true or false inside functions, I am a bit confused

I have this function, for example:

app.get('/', function(req, res) {
    var token = req.query.token;
    if(!token) {
        res.render('auth'); // Authentication
    } else {
        authorizedUsers.forEach(function(user) {
            if(user.id == token) {
                console.log('found, nickname: ' + user.nickname);
                return true;
            }
        });
        console.log('not found');
        return false;
    }
});

Basically it's looping through the authorizedUsers array, and looking for an entry where entry.id equals the token variable.

What I wanted to do is, if found, to return true and stop the execution of the rest of the app.get('/')... block.

If not found, obviously the forEach loop has already gone through all entries, and eventually the execution arrives to the printing of "not found" and return false;.

For my current code, even though an entry is found, execution continues and I still get the 'not found' log. enter image description here

Am I missing anything?

To simplify things, what I wanna do is:

  1. Looping through all authorizedUsers entries, comparing entry.id to the token variable.
  2. If found, print "found" to the console and stop the execution.
  3. If not found, print "not found" to the console and stop the execution.

Thank you.

Edit

Following Michael's solution, this is my working code:

app.get('/', function(req, res) {
    var token = req.query.token;
    if(!token) {
        res.render('auth'); // Authentication
    } else {
        if(!authorizedUsers.some(function(user) {
            if(user.id == token)
                return true;
        })) {
            console.log('No entries found.');
        } else {
            console.log('Entries found!');
        }
    }
});

Upvotes: 1

Views: 59

Answers (2)

baao
baao

Reputation: 73241

You would use Array.prototype.some for this:

authorizedUsers.some(function(user) {
    return user.id == token;
}

The some() method tests whether some element in the array passes the test implemented by the provided function.

Upvotes: 4

nbermudezs
nbermudezs

Reputation: 2844

The forEach function cannot be interrupted unless the code inside throws an exception.

So you could either do something like this

Or just let it run through all the records doing something like this:

   var found = false;
   authorizedUsers.forEach(function(user) {
        if(user.id == token) found = true;
    });
    console.log('found? ', found);

Upvotes: 0

Related Questions