当我在async
中使用await
和nodejs
时,它的响应会变得很慢PRODUCT SCHEMA
const mongoose = require('mongoose');
const productSchema = mongoose.Schema(
{
_id: mongoose.Schema.Types.ObjectId,
name: {type: String, require: true},
category_fields: { type:Object },
name_list_fields: [{ type:mongoose.Schema.Types.ObjectId, ref:'list' }],
full_name: { type:String },
actual_price: { type: Number, default: 0 },
selling_price: { type: Number, default: 0 },
product_image_url_1: { type: String, default: "" },
sku: { type: String, default: "" },
brand:{type:mongoose.Schema.Types.ObjectId, ref:'brand' },
linked_offers: [{ type:mongoose.Schema.Types.ObjectId, ref:'offer' }],
hot_deal: { type:Boolean,default:false}, });
代码
return new Promise(function(resolve, reject){
productschema.find({delete_status: { $ne: 1}})
.sort({_id:-1})
.populate('brand similar_product linked_offers','name actual_price product_image_url_1 actual_price selling_price full_name offer_image_url offer_type offer_amount_percentage description')
.skip( parseInt(req.params.index) )
.limit( parseInt(req.params.limit) )
.then(async productsrows => {
if(productsrows.length == 0){
resolve({
"success":false,
"message":"No Data"
})
}else{
try{
var arrayListOfProduct = [];
for(var i =0;i<productsrows.length;i++){
var item = productsrows[i].toObject()
item.in_stock = await commonFunctionAdmin.fetchProductCountInStock(productsrows[i]._id)
arrayListOfProduct.push(item)
}
resolve({
"success":true,
"message":"Products fetched success",
"count":await fetchTotalProductCount({delete_status: { $ne: 1}}),
"data":arrayListOfProduct
});
}catch(e){
console.log(e)
resolve({
"success":false,
"message":"something went wrong"
})
}
}
})
}) //STOCK COUNT
功能
return new Promise(function(resolve, reject){
stockSchema.aggregate([
{$unwind: "$product"},
{$unwind: "$product.imei"},
{$match: {"product.imei.sold_status":false,"product.product":ObjectId(product_id)}},
{$group: {
_id: null,
count: { $sum: 1 }
}
}]).then(async rowsTotalRevenue => {
if(rowsTotalRevenue.length > 0){
resolve(rowsTotalRevenue[0].count)
}else{
resolve(0)
}
}).catch(e=>{
console.log(e)
resolve(0)
})
});
答案 0 :(得分:0)
通常,当您使用await关键字时,您从每个请求中节省了大约200ms的时间(根据我的经验)。 要了解应用程序中正在发生的事情,您可以在功能的每个基本步骤中都放置一个计时器,从头到尾测量时间差。这非常简单,只需检查代码开始运行的时间。
异步/等待使异步代码的外观和行为更像同步代码。这就是它所有力量的所在。
我试图理解上面发布的代码,并且看到数组中有一些迭代,知道所有这些可能是答案的瓶颈。
async function myCoolFunction () {
var initial = new Date().getTime();
var finalTime;
// create a new promise inside of the async function
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve(true), 1000) // resolve
});
// wait for the promise to resolve
let result = await promise;
finalTime = newDate().getTime();
}
myCoolFunction();
}