我如何异步等待多个异步mongodb找到使用nodejs的功能
我在多个mongodb上使用“等待” .findone“一次函数一次。我想让他们全部不同步,并以某种方式知道它们何时准备使用。
而不是这样做:
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)
}
我可以做这样的事情吗?
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要跟踪并行执行多个基于承诺的异步操作的
执行。如果您想要所有结果,无论是否可能拒绝,都可以使用
Promise.allsettled()
。请参阅 doc 准确的方式其解决价值有效。For tracking the parallel execution of multiple promise-based asynchronous operations, use
Promise.all()
: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 usePromise.allSettled()
instead. See the doc for exactly how its resolved value works.