# 工具(未分类)

  1. debounce/throttle

防抖节流

定义:

export declare const debounce: <T extends (...args: any) => any>(fn: T, delay?: number) => (this: any, ...args: Parameters<T>) => Promise<ReturnType<T>>;
export declare const throttle: <T extends (...args: any) => any>(fn: T, delay?: number) => (this: any, ...args: Parameters<T>) => Promise<ReturnType<T>>;
  1. countDown/afterCountDown

倒计时,afterCountDown 返回的 Promise 将在倒计时结束后 resolve 注意:start、end 接受的参数是 Date,不是 Duration

定义:

export interface CountDownOptions {
  start?: DateLike
  end: DateLike
  interval?: number // ms
  callback?: (duration: number) => void
}

export declare const countDown: ({ start, end, interval, callback, }: CountDownOptions) => void;
export declare const afterCountDown: ({ callback: cb, ...opts }: CountDownOptions) => Promise<unknown>;

用法:

// 常规用法
countDown({
  // start: now(), // 默认值
  end: now() + 5 * 60 * 1000,
  interval: 1000,
  callback: d => this.duration = Math.ceil(d / 1000),
});

// 代替计时:setInterval(() => this.count += 10, 10);
const offset = 100000000000;
countDown({
  end: now() + offset,
  interval: 10,
  callback: n => this.count = offset - n,
});
  1. min/max

定义:

export declare const min: (a: number, b: number) => number;
export declare const max: (a: number, b: number) => number;
  1. debugPromise

调试 Promise

定义:

export declare const debugPromise: <T = any>(p: Promise<T>, debug?: Function | undefined) => Promise<T>;

用法:

let times = 0;
const debugFn = isDebuging
  ? (v: any) => {
    // 该函数会在每一次 then 之前执行,但不会参与值的变更,可在此处打 log 进行调试,查看 Promise 链的变化
    times += 1;
    slugConsole.log(`debugPromise times(${times}) = ${v}`);
  }
  // 当为 undefined 时,停止注入原 Promise
  : undefined;
const p = debugPromise(new Promise<number>((r) => r(0)), debugFn);
const v = await p.then(v => v + 1).then(v => v + 3).then(v => v + 2).then();
expect(times).toBe(5);
expect(v).toBe(6);
  1. retry

操作重试

定义:

export interface RetryOptions<T> {
    fn: () => Promise<T>;
    delay: number;
    times: number;
}
export interface RetryResponse<T> {
    data?: T;
    err?: any;
}
export declare const retry: <T = any>({ fn, times, delay, }: RetryOptions<T>) => Promise<RetryResponse<T>>;

用法:

const { data, err } = await retry({
  fn: async () => 1,
  times: 2,
  delay: 100,
})
  1. promisify

本方法使用了 ts4.2 新语法优化了类型定义书写

  • https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-2.html#leadingmiddle-rest-elements-in-tuple-types

定义:

export declare type ErrorFirstCallback<T> = (err: any, arg: T) => void;
export declare type PromisifyLegacy<Args extends any[], T> = (...args: [...arr: Args, cb: ErrorFirstCallback<T>]) => void;
export interface CustomPromisifyLegacy<Args extends any[], T> extends Function {
    __promisify__: (...args: Args) => Promise<T>;
}
export declare function promisify<Args extends any[], T>(fn: PromisifyLegacy<Args, T> | CustomPromisifyLegacy<Args, T>): (...args: Args) => Promise<T>;
更新于: 8/26/2021, 11:01:49 AM