“continue” in cursor.forEach()

前端 未结 5 580
猫巷女王i
猫巷女王i 2020-12-12 14:04

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

相关标签:
5条回答
  • 2020-12-12 14:29

    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();
    });
    
    0 讨论(0)
  • 2020-12-12 14:43

    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.

    0 讨论(0)
  • 2020-12-12 14:44

    Making use of JavaScripts short-circuit evaluation. If el.shouldBeProcessed returns true, doSomeLengthyOperation

    elementsCollection.forEach( el => 
      el.shouldBeProcessed && doSomeLengthyOperation()
    );
    
    0 讨论(0)
  • 2020-12-12 14:54

    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)
        }
    
    });
    
    })()
    
    0 讨论(0)
  • 2020-12-12 14:54

    Use continue statement instead of return to skip an iteration in JS loops.

    0 讨论(0)
提交回复
热议问题