"continuar" en el cursor.forEach()


Estoy construyendo una aplicación usando meteor.js y MongoDB y yo tenemos una pregunta sobre cursor.forEach (). Quiero comprobar algunas condiciones al principio de cada iteración forEach y luego omitir el elemento si no tengo que hacer la operación en él para que pueda ahorrar algo de tiempo.

Aquí está mi código:

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

Sé que podría convertir el cursor a array usando cursor.encontrar().fetch () y luego use regular for-loop para iterar sobre elementos y use continue y break normalmente pero estoy interesado si hay algo similar para usar en forEach ().

Author: Drag0, 2013-08-27

2 answers

Cada iteración de la forEach() llamará a la función que ha suministrado. Para detener el procesamiento posterior dentro de cualquier iteración dada (y continuar con el siguiente elemento) solo tiene que return desde la función en el punto apropiado:

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

  // This part will be avoided if not neccessary
  doSomeLengthyOperation();
});
 377
Author: nnnnnn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-27 00:40:48

En mi opinión, el mejor enfoque para lograr esto mediante el uso de la filter method ya que no tiene sentido regresar en un bloque forEach; para un ejemplo en su fragmento:

// Fetch all objects in SomeElements collection
var elementsCollection = SomeElements.find();
elementsCollection
.filter(function(element) {
  return element.shouldBeProcessed;
})
.forEach(function(element){
  doSomeLengthyOperation();
});

Esto reducirá su elementsCollection y solo mantendrá los elementos filtred que deben procesarse.

 5
Author: Ramy Tamer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-12 02:15:47