javascript - 看起来像猫鼬查询的 Promise.all() 与顺序等待一样花费时间
问题描述
我被困在Promise.all
猫await
鼬查询中。
我尝试在我的两个代码之间进行基准测试,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 倍。请讨论原因。
解决方案
Promise.all
你的理解async/await
是正确的。
后台发生了一些事情,也许this.where
最终以某种队列结束,并且组件逻辑无论如何都只是一个一个地执行。
您是否还可以包含更多代码,以便我们可以看到实际this
的上下文是什么?
或者 MongoDB 被每个查询完全占用 100%,因此一次转换所有查询可能会更糟,因为它必须在所有查询之间进行交换。
推荐阅读
- javascript - Thingsboard_导航到新仪表板状态_Widget 自定义操作_Javascript 代码
- c# - 从仅包含不同项目的两个列表创建新列表?
- excel - 合并方法 - VBA
- css - BEM 中的元素是否需要在块内?
- python - 使用 FTP 从服务器中使用 python 删除文件
- c# - JsonConvert.SerializeObject 抛出自引用错误
- wpf - WPF单选按钮图标更改(圆圈本身)
- javascript - 如何在按钮单击时更改不同组件的样式?
- r - 拟合 knn 时出错
- symfony - Symfony 4 CollectionType 具有多个带有默认值的下拉列表