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().
This question is related to
javascript
mongodb
foreach
meteor
Making use of JavaScripts short-circuit evaluation. If el.shouldBeProcessed
returns true, doSomeLengthyOperation
elementsCollection.forEach( el =>
el.shouldBeProcessed && 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.
Use continue statement instead of return to skip an iteration in JS loops.
Here is a solution using for of
and continue
instead of forEach
:
let elementsCollection = SomeElements.find();
for (let el of elementsCollection) {
// continue will exit out of the current
// iteration and continue on to the next
if (!el.shouldBeProcessed){
continue;
}
doSomeLengthyOperation();
});
This may be a bit more useful if you need to use asynchronous functions inside your loop which do not work inside forEach
. For example:
(async fuction(){
for (let el of elementsCollection) {
if (!el.shouldBeProcessed){
continue;
}
let res;
try {
res = await doSomeLengthyAsyncOperation();
} catch (err) {
return Promise.reject(err)
}
});
})()
Source: Stackoverflow.com