Search code examples
node.jsmongoose

How to handle errors in for await


So I have this node/mongodb app with this function:

const myFuncDoesALotOfThings = async () => {
    try{
        await CollectionA.deleteMany({});
        await CollectionB.deleteMany({});
        const allCollectionsC = CollectionsC.find({'country': "UK"});   
        for await (const coll of allCollectionsC){
            if(coll.city === 'London'){
                await doSomeMongoDbOperation(); 
            }
        }
    }
    catch(exception){
        console.log("exception",exception);
        //here I think I want to resume
    }
}

My concern is about the failure of await doSomeMongoDbOperation();. How can I make sure that exception on one single await doSomeMongoDbOperation(); will not stop the iteration?


Solution

  • wrap another try catch around your api so it won't stop the iteration.

    const myFuncDoesALotOfThings = async () => {
        try{
            await CollectionA.deleteMany({});
            await CollectionB.deleteMany({});
            const allCollectionsC = CollectionsC.find({'country': "UK"});   
            for await (const coll of allCollectionsC){
                if(coll.city === 'London'){
                  try{
                    await doSomeMongoDbOperation(); 
                    } catch(e){
                       console.log("mongo operation failed")
                    }
                }
            }
        }
        catch(exception){
            console.log("exception",exception);
            //here I think I want to resume
        }
    }