每个函数在 promis.all 中花费多少时间? [英] how much time each function takes in promis.all?

查看:37
本文介绍了每个函数在 promis.all 中花费多少时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 URL,我想同时调用它们.我想知道每个请求需要多长时间?我的代码是这样的:

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]);
})

我想要的是这样的

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

有什么办法可以得到这个时间吗?

is there any way to get this time?

推荐答案

非常简单,你的 .map 函子为每个 axios 请求的开始时间提供了可靠的关闭机会,允许计算在请求的 .then 回调中减去所花费的时间.

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);
});

这篇关于每个函数在 promis.all 中花费多少时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆