// Promise 创建(自动超时取消)
export function getTimeoutPromise<T extends Object, E extends Error>(timeout?: number) {
  let resolve: (t: T) => void = () => {};
  let rejected: (e: E) => void = () => {};
  let finished = false;

  const promise = new Promise<T>((res, _rej) => {
    resolve = (t: T) => {
      if (!finished) {
        finished = true;
        res(t);
      }
    };
    rejected = (e: E) => {
      if (!finished) {
        finished = true;
        _rej(e);
      }
    };

    if (typeof timeout === "number") {
      setTimeout(() => {
        rejected(new Error("timeout") as any);
      }, timeout);
    }
  }).finally(() => {
    finished = true;
  });

  return {
    // @ts-ignore
    promise,
    resolve,
    rejected,
  };
}

// 延时
export const delay = (time: number) => new Promise(resolve => setTimeout(resolve, time));
