Home > Software design >  how to call async function inside then() block along with finally() in MongoDB Driver?
how to call async function inside then() block along with finally() in MongoDB Driver?

Time:11-26

I am learning MongoDB in Node.js. I have a main function which returns the collection object pointing to the desired collection.

main()
    .then((collection) => {
        findDocs(collection)
    })
    .catch(console.error);
    .finally(() => client.close());

I am calling findDocs function by passing the collection object. But this fails with PoolClosedError [MongoPoolClosedError]: Attempted to check out a connection from closed connection pool error. But if I remove finally() block, it works fine but the database connection doesn't close, as anyone would expect.

Is there a way around this problem or suggestions for calling the callback async function better?

CodePudding user response:

You must use async-await to solve your problem:

here an example

main()
    .then(async (collection) => {
        await findDocs(collection)
    })
    .catch(console.error);
    .finally(() => client.close());

or instead of using then/catch closure use the try-catch closure in the function that calls the main function:

Example:

async function index(){
  try{
   const collection = await main();
   const docs = await  findDocs(collection)

  }catch(e){
    console.error(e)
  }finally{
    client.close()
  }

}

Another option is closing the client when findDocs end:

main()
  .then((collection) => {
    findDocs(collection)
      .catch(console.error)
      .finally(() => client.close());
  })
  .catch(console.error);
  • Related