I'm building an app using meteor.js and MongoDB and I have a question about cursor.forEach(). I want to check some conditions in the beginning of each forEach iteration and then skip the element if I don't have to do the operation on it so I can save some time.
Here is my code:
// Fetch all objects in SomeElements collection var elementsCollection = SomeElements.find(); elementsCollection.forEach(function(element){ if (element.shouldBeProcessed == false){ // Here I would like to continue to the next element if this one // doesn't have to be processed }else{ // This part should be avoided if not neccessary doSomeLengthyOperation(); } });
I know I could turn cursor to array using cursor.find().fetch() and then use regular for-loop to iterate over elements and use continue and break normally but I'm interested if there is something similiar to use in forEach().
To continue in a JavaScript forEach loop you can't use the continue statement because you will get an error. Instead you will need to use the return statement in place of the continue statement because it will act in the same way when using a forEach because you pass in a callback into the forEach statement.
Use return For practical purposes, return in a forEach() callback is equivalent to continue in a conventional for loop. When you return , you skip the rest of the forEach() callback and JavaScript goes on to the next iteration of the loop.
There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.
Each iteration of the forEach()
will call the function that you have supplied. To stop further processing within any given iteration (and continue with the next item) you just have to return
from the function at the appropriate point:
elementsCollection.forEach(function(element){ if (!element.shouldBeProcessed) return; // stop processing this iteration // This part will be avoided if not neccessary doSomeLengthyOperation(); });
In my opinion the best approach to achieve this by using the filter
method as it's meaningless to return in a forEach
block; for an example on your snippet:
// Fetch all objects in SomeElements collection var elementsCollection = SomeElements.find(); elementsCollection .filter(function(element) { return element.shouldBeProcessed; }) .forEach(function(element){ doSomeLengthyOperation(); });
This will narrow down your elementsCollection
and just keep the filtred
elements that should be processed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With