0

I have some URLs and I want to call each of them simultaneous. I want to know how much time each request takes? my code like this:

var urls=["http://req0.com","http://req1.com","http://req2.com"];
Promis.all(urls.map(e=>return axios.post(e,{test:""test}).catch(err=>return e)).then(
(values)=>{
console.log(values[0]);
console.log(values[1]);
console.log(values[2]);
})

what I want is something like this

conosle.log(value[0].responseTime);
conosle.log(value[1].responseTime)
conosle.log(value[2].responseTime)

is there any way to get this time?

m.eslampnah
  • 169
  • 1
  • 4
  • 10
  • google is quicker than so: https://stackoverflow.com/questions/49874594/how-to-get-response-times-from-axios – Estradiaz Feb 08 '20 at 12:53

2 Answers2

0

you can use async/await and measure the time with console.time(), console.timeEnd().

async getPost(){
 const url = 'https://jsonplaceholder.typicode.com/posts?_start=1';
 console.time();
 const post = await axios.get(url);
 console.timeEnd();
 return post;
};

const post = getPost();
console.log(`post ${post}`);

Ravi Singh
  • 1,049
  • 1
  • 10
  • 25
0

Pretty simple, your .map functor offers the opportunity for a reliable closure for the start time of each axios request, allowing calculation of time taken by subtraction in the requests' .then callback.

var urls = ["http://req0.com","http://req1.com","http://req2.com"];
Promise.all(urls.map(e => {
    let start = Date.now();
    return axios.post(e, {test:'test'})
    .then(value => ( { value, t: Date.now() - start} ));
}))
.then((timedValues) => {
    let times = timedValues.map(x => x.t);
    let values = timedValues.map(x => x.value);
    console.log(times);
    console.log(values);
});

If you wish to include the timing of errors, then it's only slightly more complicated:

var urls=["http://req0.com","http://req1.com","http://req2.com"];
Promise.all(urls.map(e => {
    let t = Date.now();
    return axios.post(e, {test:"test"})
    .then(value => ( { outcome:'success', value, t:Date.now() - t} ))
    .catch(error => ( { outcome:'error', error, t:Date.now() - t} ));
}))
.then((timedOutcomes) => {
    let times = timedOutcomes.map(x => x.t);
    let values = timedOutcomes.filter(x => x.outcome === 'success').map(x => x.value);
    let errors = timedOutcomes.filter(x => x.outcome === 'error').map(x => x.error);
    console.log(times);
    console.log(values);
    console.log(errors);
});
Roamer-1888
  • 19,138
  • 5
  • 33
  • 44