I’m playing with Node.js and Mongoose — trying to find specific comment in deep comments nesting with recursive function and forEach within. Is there a way to stop Node.js forEach? As I understand every forEach iteration is a function and and I can’t just do break, only return but this won’t stop forEach.
function recurs(comment) {
comment.comments.forEach(function(elem) {
recurs(elem);
//if(...) break;
});
}
You can’t break from a
forEach. I can think of three ways to fake it, though.1. The Ugly Way: pass a second argument to
forEachto use as context, and store a boolean in there, then use anif. This looks awful.2. The Controversial Way: surround the whole thing in a
try-catchblock and throw an exception when you want to break. This looks pretty bad and may affect performance, but can be encapsulated.3. The Fun Way: use
every().You can use
some()instead, if you’d ratherreturn trueto break.