Determine which promise is slowest in Promises.all

耗尽温柔 提交于 2019-12-12 02:44:09

问题


I have been using Promise.all in my app. For the purpose of improving app speed, how to determine which promise is the slowest?

const result = await Promise.all([
          this.props.fetchUser(),
          this.props.cacheResourcesAsync(),
          this.props.initAmplitude(),
          this.props.initAppVariables(),
        ]);

回答1:


You can use a helper function for that:

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

Then write

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"),
]);



回答2:


I'd do something like this :

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


来源:https://stackoverflow.com/questions/43861636/determine-which-promise-is-slowest-in-promises-all

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