为什么使用 Async 时 Api 响应很慢 等待与 mongodb.



当我在nodejs中使用asyncawait时,它的响应很慢 产品架构

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)
      })
    });

通常,当您使用 await 关键字时,您会从每个请求中节省大约 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();
}

最新更新