“continue” in cursor.forEach()

前端 未结 5 582
猫巷女王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: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)
        }
    
    });
    
    })()
    

提交回复
热议问题