装饰异步功能的正确方法 [英] Proper way to decorate async function

查看:45
本文介绍了装饰异步功能的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个函数装饰器,并测量异步函数的执行时间,并返回解析或拒绝缩进的结果而不进行装饰.任何线索如何实现这一目标?大多数指南都是关于同步功能的,它们并没有触及异步世界.

I want to make a function decorator and measure async's function execution time, and return resolve or reject results as indented without decorating. Any clue how to achieve this? Most guides are about sync functions and are not touching the async world.

这是一个说明所需功能的示例

This is an example to illustrate the desired functionality

async exampleFunction () {
try{
  const response = await aPromise() // The goals is to measure this one with a decorator measure(aPromise) and dispatch actions if the fetching takes a long time
}
catch (err){
  // Do something with error
}

推荐答案

这是一个高阶函数,可以通过履行或拒绝来衡量返回的诺言兑现所需的时间:

Here's a higher-order function that can measure the time it takes for the returned promise to settle either by fulfilling or rejecting:

function measure(fn) {
  return async (...args) => {
    const begin = performance.now();
    try {
      return await fn(...args);
    } finally {
      const end = performance.now();
      console.log(`Execution time: ${end - begin}`);
    }
  };
}

示例用法:

exampleFunction();

async function exampleFunction() {
  try {
    const value = await measure(defer)('foo', 1000);
    // where normally you'd write:
    // const value = await defer('foo', 1000);
    console.log(`Resolved with ${value}`);
  } catch (reason) {
    console.log(`Rejected with ${reason}`);
  }
}

function measure(fn) {
  return async (...args) => {
    const begin = performance.now();
    try {
      return await fn(...args);
    } finally {
      const end = performance.now();
      console.log(`Execution time: ${end - begin}`);
    }
  };
}

function defer(result, ms) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const settle = Math.random() < 0.5 ? resolve : reject;
      settle(result);
    }, ms);
  });
}

这篇关于装饰异步功能的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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