【问题标题】:calculate execution time in callback functions nodejs在回调函数nodejs中计算执行时间
【发布时间】:2021-06-05 06:30:03
【问题描述】:

我需要在回调函数中计算执行时间?

用例

在我的 nodejs 应用程序中,有一个 REST API 端点负责读取文件并写入数据库。这个过程应该发生在服务器后台用户不等待响应。像发出 API 请求 -> 启动过程 -> 响应用户通知过程开始的过程。我没有使用等待,所有都由回调处理。请找到下面的伪代码来了解一下。

function callbackRetry(error, data){
  if(data.hasFailedItems){
     saveDataToDb(data.failedItems)
  }
}

function saveDataToDb(params){
  dbSdkSaveData(params, (error, data) => callbackRetry(error, data))
}

router.get('/',(req, res, next) => {
  forEach( reading file line by line ) {
     const params = line;
     saveDataToDb(params)
  }
  
  res.json({message : 'process successfully executed!'})
}

我只想计算完成这些db保存和retr操作消耗了多少时间。

【问题讨论】:

    标签: node.js


    【解决方案1】:

    我会使用performance 模块。使用日志记录位置以获得所需的结果

    const { performance } = require('perf_hooks');
    
    function callbackRetry(error, data){
      if(data.hasFailedItems){
         saveDataToDb(data.failedItems)
      }
    }
    
    function saveDataToDb(params){
      dbSdkSaveData(params, (error, data) => callbackRetry(error, data))
    }
    
    router.get('/',(req, res, next) => {
      const t0 = performance.now()
      forEach( reading file line by line ) {
         const params = line;
         saveDataToDb(params)
      }
      const t1 = performance.now()
      console.log("Execution time:" + (t1 - t0) + " milliseconds.")
      res.json({message : 'process successfully executed!'})
    }
    
    

    【讨论】:

      猜你喜欢
      • 2021-07-15
      • 2015-07-19
      • 2011-10-21
      • 1970-01-01
      • 1970-01-01
      • 2017-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多