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

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

问题描述

我正在使用meteor.js 和MongoDB 构建一个应用程序,我有一个关于cursor.forEach() 的问题.我想在每次 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.

这是我的代码:

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

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

推荐答案

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

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天全站免登陆