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.
Am I missing anything?
To simplify things, what I wanna do is:
- Looping through all authorizedUsers entries, comparing entry.id to the token variable.
- If found, print "found" to the console and stop the execution.
- 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!');
}
}
});