mongoose 如何处理for await中的错误

9udxz4iz  于 2023-02-08  发布在  Go
关注(0)|答案(1)|浏览(126)

我有一个node/mongodb应用程序,它具有以下功能:

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
    }
}

我关心的是await doSomeMongoDbOperation();的失败,如何确保单个await doSomeMongoDbOperation();上的异常不会停止迭代?

vd8tlhqk

vd8tlhqk1#

在API周围 Package 另一个try catch,这样它就不会停止迭代。

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
    }
}

相关问题