Javascript 为什么在mongodb中使用Async await时Api响应缓慢
当我在Javascript 为什么在mongodb中使用Async await时Api响应缓慢,javascript,node.js,mongodb,mongoose,async-await,Javascript,Node.js,Mongodb,Mongoose,Async Await,当我在nodejs中使用async和wait时,它的响应是慢产品模式 const mongoose = require('mongoose'); const productSchema = mongoose.Schema( { _id: mongoose.Schema.Types.ObjectId, name: {type: String, require: true}, category_fields: { type:Object }, name_list_field
nodejs
中使用async
和wait
时,它的响应是慢产品模式
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}, });
代码
通常,当您使用wait关键字时,您会从每个请求中保存大约200毫秒(我的经验)。 为了了解应用程序中发生了什么,您可以在函数的每个基本步骤中设置计时器,测量从开始到结束的时间差。这非常简单,只需检查代码开始运行的时间 Async/await使异步代码的外观和行为更像同步代码。这就是它的全部力量所在 我试着理解上面发布的代码,看到数组中有一些迭代,知道所有这些都可能是答案的瓶颈
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();
}
在我的例子中,问题是mongodb服务器不安全,所以api响应很慢,现在工作正常
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)
})
});
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();
}