首页 > 解决方案 > 看起来像猫鼬查询的 Promise.all() 与顺序等待一样花费时间

问题描述

我被困在Promise.allawait鼬查询中。

我尝试在我的两个代码之间进行基准测试,async/await并且Promise.all花费相同的时间。

我提供了一些我的代码。在第一部分,我尝试使用 promise.all,最后我尝试使用 await,这就是结果

sep: 2890.802ms
sep-await: 2409.150ms
console.time('sep')
  const [New, CreatingQuotation, CreatingInvoiceCoverage, CarChecking, Completed, Cancelled] = await Promise.all([
    this.where('State', 'new').countDocuments().exec(),
    this.where('State', 'creating_quotation').countDocuments().exec(),
    this.where('State', 'creation_invoice_coverage').countDocuments().exec(),
    this.where('State', 'car_checking').countDocuments().exec(),
    this.where('State', 'completed').countDocuments().exec(),
    this.where('State', 'cancelled').countDocuments().exec(),
  ])
  console.timeEnd('sep')


  console.time('sep-await')
  const NewX = await this.where('State', 'new').countDocuments().exec()
  const CreatingQuotationX = await this.where('State', 'creating_quotation').countDocuments().exec()
  const CreatingInvoiceCoverageX = await this.where('State', 'creation_invoice_coverage').countDocuments().exec()
  const CarCheckingX = await this.where('State', 'car_checking').countDocuments().exec()
  const CompletedX = await this.where('State', 'completed').countDocuments().exec()
  const CancelledX = await this.where('State', 'cancelled').countDocuments().exec()
  console.timeEnd('sep-await')

我认为Promise.all应该比await预期的快 5 倍。请讨论原因。

标签: javascriptnode.jsmongoose

解决方案


Promise.all你的理解async/await是正确的。

后台发生了一些事情,也许this.where最终以某种队列结束,并且组件逻辑无论如何都只是一个一个地执行。

您是否还可以包含更多代码,以便我们可以看到实际this的上下文是什么?


或者 MongoDB 被每个查询完全占用 100%,因此一次转换所有查询可能会更糟,因为它必须在所有查询之间进行交换。


推荐阅读