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?
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.
CodePudding user response:
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.