1

I am using "await" on multiple MongoDB ".findOne" functions to different collections one at a time. I would like to let them all run asynchronously 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?

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.

1
  • 1
    How about using Promise.all or promise.allsettled? Commented Jun 11, 2022 at 2:12

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.