【问题标题】:Why Api response is slow when using Async await with mongodb为什么在使用 Async await 和 mongodb 时 Api 响应很慢
【发布时间】:2019-10-22 20:47:24
【问题描述】:

当我在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)
      })
    });

【问题讨论】:

    标签: javascript node.js mongodb mongoose async-await


    【解决方案1】:

    通常当您使用 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();
    
    }
    

    【讨论】:

    • 在我的案例中,问题是 mongodb 服务器不安全,因此 api 响应很慢,现在它工作正常
    猜你喜欢
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 2020-05-03
    • 2017-10-26
    • 2012-08-27
    • 1970-01-01
    相关资源
    最近更新 更多