【问题标题】:Trying to code custom Throttling function on Typescript尝试在 Typescript 上编写自定义节流功能
【发布时间】:2022-01-05 09:14:43
【问题描述】:

我有以下功能非常好

do {
    try {
        const { assets } = await myApi(arg1, arg2, arg3);     <<--  
        return assets; 
    } catch (err: any) {
        if (err.response.status == 429) {
            await sleep(300);
            console.log('Throttle happened, sleeping for 300ms');
        } else
            throw (err);
    }
}
while (true);

我想把这个方法通用化,用下面的方式调用

throttleHandler(myApi, ...args)

我进行了一些尝试,但打字稿抱怨它。我也不确定我是否做得正确。而且我不想使用any。我需要输入它。

type ThrottleHandler<TOut> = (...args: any) => TOut;

async function throttleHandler<T>(promiseFunction: ThrottleHandler<T>, ...args: any): Promise<T> {
  console.log("args", args, ...args)
  do {
    try {
      return await promiseFunction(...args);
    } catch (err: any) {

      if (err.response.status == 429) {
        await sleep(300);
        console.log('Throttle happened, sleeping for 300ms');
      } else
        throw (err);
    }
  }
  while (true);
}

【问题讨论】:

    标签: typescript typescript-typings typescript-generics


    【解决方案1】:
    type PromiseFn = (...args: any[]) => Promise<any>;
    type UnwrappedReturnType<T extends PromiseFn> = T extends (...args: any) => Promise<infer R> ? R : any
    
    async function throttleHandler<ApiFn extends PromiseFn>(
      promiseFunction: ApiFn,
      ...args: Parameters<ApiFn>
    ): Promise<UnwrappedReturnType<ApiFn>> {
      console.log("args", args, ...args)
      do {
        try {
          return await promiseFunction(...args);
        } catch (err: any) {
    
          if (err.response.status == 429) {
            await sleep(300);
            console.log('Throttle happened, sleeping for 300ms');
          } else
            throw (err);
        }
      }
      while (true);
    }
    
    const k = (arg1: string, arg2: number) => {
      console.log(arg1);
      return Promise.resolve(true);
    }
    
    const f = throttleHandler(k, 'param', 12);
    

    以前的版本使用新的 TS 4.5 Awaited 类型,但这个在所有最新版本中都一样有效。

    Playground Link

    【讨论】:

    • 感谢您的回答,但我认为如果您可以包含一些 cmets 和键入声明的解释,您的回答会更有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2018-02-10
    • 1970-01-01
    • 2020-03-06
    • 2021-01-11
    • 1970-01-01
    • 2018-04-03
    相关资源
    最近更新 更多