我一直在我的应用中使用Promise.all。 为了提高应用程序速度,如何确定哪个承诺最慢?
const result = await Promise.all([
this.props.fetchUser(),
this.props.cacheResourcesAsync(),
this.props.initAmplitude(),
this.props.initAppVariables(),
]);
答案 0 :(得分:3)
您可以使用辅助函数:
async function time(p, name) {
const start = Date.now();
try {
return await p;
} finally {
const end = Date.now();
console.log(`${name} took ${end-start}ms`);
}
}
然后写
const result = await Promise.all([
time(this.props.fetchUser(), "user"),
time(this.props.cacheResourcesAsync(), "cacheResources"),
time(this.props.initAmplitude(), "amplitude"),
time(this.props.initAppVariables(), "appVars"),
]);
答案 1 :(得分:2)
我会做这样的事情:
let startTime = new Date();
Promise.all([
this.fetchUser().then(() => {
console.log('fetch user takes', new Date().getTime()-startTime.getTime());
return arguments;}),
this.fetchData().then(() => {
console.log('fetchData takes', new Date().getTime()-startTime.getTime());
return arguments;})
]);