Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"continue" in cursor.forEach()

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().

like image 859
Drag0 Avatar asked Aug 26 '13 21:08

Drag0


People also ask

Does continue work 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.

How do you continue in forEach?

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.

How do you break a forEach 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.


2 Answers

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(); }); 
like image 54
nnnnnn Avatar answered Sep 21 '22 18:09

nnnnnn


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.

like image 42
Ramy Tamer Avatar answered Sep 21 '22 18:09

Ramy Tamer