How to get response times from Axios

纵然是瞬间 提交于 2019-12-05 04:13:27
Sagar M

You can use the interceptor concept of axios.

Request intercepor will set startTime

axios.interceptors.request.use(function (config) {

  config.metadata = { startTime: new Date()}
  return config;
}, function (error) {
  return Promise.reject(error);
});

Response interceptor will set endTime & calculate the duration

axios.interceptors.response.use(function (response) {

  response.config.metadata.endTime = new Date()
  response.duration = response.config.metadata.endTime - response.config.metadata.startTime
  return response;
}, function (error) {
  error.config.metadata.endTime = new Date();
  error.duration = error.config.metadata.endTime - error.config.metadata.startTime;
  return Promise.reject(error);
});

Its way long after but this is my simple workaround

function performSearch() {
        var start = Date.now();
        var url='http://example.com';
        var query='hello';
        axios.post(url,{'par1':query})
            .then(function (res) {
                var millis = Date.now() - start;
                $('.timer').html(""+Math.floor(millis/1000)+"s")
            })
            .catch(function (res) {
                console.log(res)
            })


    }

this is my workaround

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!