How to measure the execution time of a promise?

前端 未结 4 1851
迷失自我
迷失自我 2020-12-03 15:05

I\'m trying to write a function that measures the execution time of another function:

export class Profiler {
    public measureSyncFunc(fn: () => any): P         


        
4条回答
  •  半阙折子戏
    2020-12-03 15:48

    Here's a simple wrapper function I wrote. It returns a Promise (via the async keyword), and so you can just call it with your promise. I added the time value as a property to the response. If you cannot have that value in the response, then you would need to remove it afterwards.

    const stopwatchWrapper = async (promise) => {
      const startTime = Date.now()
      const resp = await promise
      resp.executionTime = Date.now() - startTime
      return resp
    }
    
    const axiosPromise = stopwatchWrapper(axios(reqSelected))
    const response = await axiosPromise
    console.log(response.executionTime)
    

提交回复
热议问题