Ada*_*olt 5 javascript asynchronous node.js promise es6-promise
我正在做一些性能测试,并正在查看node / js中的Promise.all()。但是,在测试之后,它实际上比使用await来解决我要解决的3个承诺要慢。我只是从mongodb数据库返回一些数据。
我在这里做错什么了吗,还是因为事件循环的工作方式?
Promise.all():234.820ms
// Init db connection
const db = client.db('docker-client1');
const productsCollection = db.collection('ICProductData');
const rulesCollection = db.collection('SPRuleData');
const customersCollection = db.collection('ARCustomerData');
// Main function
const CustomerCode = 'FINE';
const ProductCode = 'BEDCABINET';
let customers = customersCollection
.find({ _id: CustomerCode })
.project({ PriceCode: 1, BillToAccountCode: 1 })
.toArray();
let products = productsCollection
.find({ _id: ProductCode })
.project({ 'Price.PriceCode': 1, 'Price.SellingPrice': 1 })
.toArray();
let rules = rulesCollection
.find({
$and: [
{
$or: [
{
$and: [
{ What1Code: ProductCode, What1Type: 'Product' },
{ Who1Code: CustomerCode, Who1Type: 'Customer' }
]
}
]
}
]
})
.toArray();
const results = await Promise.all([customers, products, rules]);
console.timeEnd();
Run Code Online (Sandbox Code Playgroud)
只需使用await:127.239ms
// Init db connection
const db = client.db('docker-client1');
const productsCollection = db.collection('ICProductData');
const rulesCollection = db.collection('SPRuleData');
const customersCollection = db.collection('ARCustomerData');
// Main function
const CustomerCode = 'FINE';
const ProductCode = 'BEDCABINET';
const custReq = await customersCollection
.find({ _id: CustomerCode })
.project({ PriceCode: 1, BillToAccountCode: 1 })
.toArray();
const prodReq = await productsCollection
.find({ _id: ProductCode })
.project({ 'Price.PriceCode': 1, 'Price.SellingPrice': 1 })
.toArray();
let rulesReq = await rulesCollection
.find({
$and: [
{
$or: [
{
$and: [
{ What1Code: ProductCode, What1Type: 'Product' },
{ Who1Code: CustomerCode, Who1Type: 'Customer' }
]
}
]
}
]
})
.toArray();
console.timeEnd();
Run Code Online (Sandbox Code Playgroud)
Jos*_*rin -2
在旧版本的 Mongo 中,toArray() 方法不会返回 Promise。这可能是关于时间安排的解释。您可以在每个 toArray() 之后放置一个带有计时的 console.log,它们应该在相同的毫秒内运行(相同的刻度)。如果情况并非如此,则可能表明 toArray() 正在等待响应......因此您正在按顺序运行。您可以尝试使用以下方法解决此问题:let myProm = collection.find(filter).exec()
| 归档时间: |
|
| 查看次数: |
339 次 |
| 最近记录: |