Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading