"继续]在cursor.forEach() [英] "continue" in cursor.forEach()

查看:146
本文介绍了"继续]在cursor.forEach()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用meteor.js和MongoDB构建一个应用程序,我对cursor.forEach()有个疑问。
我想检查每个forEach迭代开始时的一些条件,然后跳过元素,如果我不必对它进行操作,那么我可以节省一些时间。

下面是我的代码:

  //获取SomeElements集合中的所有对象
var elementsCollection = SomeElements.find();
elementsCollection.forEach(function(element){
if(element.shouldBeProcessed == false){
//这里我想继续下一个元素,如果这个
//不必处理
} else {
//这个部分应该避免,如果不需要
doSomeLengthyOperation();
}
});

我知道我可以使用cursor.find()。fetch()定期for循环遍历元素和使用继续和正常打破,但我感兴趣,如果有类似的东西在forEach()使用。

解决方案 $ forEach()的每次迭代都会调用您提供的函数。要在任何给定的迭代中停止进一步的处理(并继续下一个项目),您只需在适当的位置从函数返回

  elementsCollection.forEach(function(element){
if(!element.shouldBeProcessed)
return; //停止处理这个迭代

//这个部分如果不是必须的话可以避免
doSomeLengthyOperation();
});


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

解决方案

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();
});

这篇关于"继续]在cursor.forEach()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆