微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

cursor.forEach() 中的“继续”

如何解决cursor.forEach() 中的“继续”

的每次迭代都forEach()调用您提供的函数。要在任何给定的迭代中停止进一步处理(并继续下一项),您只需return在适当的点从函数中执行:

elementsCollection.forEach(function(element){
  if (!element.shouldBeProcessed)
    return; // stop processing this iteration

  // This part will be avoided if not neccessary
  doSomeLengthyOperation();
});

解决方法

我正在使用meteor.js 和MongoDB 构建一个应用程序,我有一个关于cursor.forEach() 的问题。我想在每次 forEach
迭代开始时检查一些条件,然后如果我不需要对其进行操作则跳过该元素,这样我可以节省一些时间。

这是我的代码:

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

我知道我可以使用 cursor.find().fetch() 将光标转换为数组,然后使用常规 for 循环遍历元素并正常使用 continue 和
break 但我很感兴趣是否在 forEach( )。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。