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 can I async await multiple synchronous MongoDB findOne functions with NodeJS

I am using "await" on multiple MongoDB ".findOne" functions to different collections one at a time. I would like to let them all run synchronously together and somehow know when they are all ready to use.

Instead of doing this:

async function myFunction() {
    const collection_1 = await firstCollection.findOne({})
    const collection_2 = await secondCollection.findOne({})
    const collection_3 = await thirdCollection.findOne({})

    console.log(collection_1, collection_2, collection_3)
  }

Can I do something like this?

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

async function myFunction() {
    [collection_1, collection_2, collection_3]
    
    await new Promise(() => {
      collection_1 = firstCollection.findOne({})
      collection_2 = secondCollection.findOne({})
      collection_3 = thirdCollection.findOne({})
    })

    console.log(collection_1, collection_2, collection_3)
  }

I don’t know how to correctly use Promises to do this.

>Solution :

For tracking the parallel execution of multiple promise-based asynchronous operations, use Promise.all():

async function myFunction() {
    const [collection_1, collection_2, collection_3] = await Promise.all([
        firstCollection.findOne({}), 
        secondCollection.findOne({}), 
        thirdCollection.findOne({})
    ]);
    console.log(collection_1, collection_2, collection_3)
}

Promise.all() will reject if any of the promises you pass it reject. If you want all results, regardless of whether one might reject, you can use Promise.allSettled() instead. See the doc for exactly how its resolved value works.

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