我如何异步等待多个异步mongodb找到使用nodejs的功能

发布于 2025-02-06 10:05:49 字数 785 浏览 1 评论 0原文

我在多个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尽揽少女心 2025-02-13 10:05:49

要跟踪并行执行多个基于承诺的异步操作的

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.allsettled()。请参阅 doc 准确的方式其解决价值有效。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文