前端排队请求

enum ShowStopDialogRes {
  cancle,
  sure,
}
interface Counter {
  total: number;
  ended: number;
  error: number;
  success: number;
}
interface CodeObj<T> {
  Data: T;
  Msg: string | null;
  Code: number;
}
class QueueRequest {
  hasStopDialog: boolean;
  isShow: boolean;
  isStop: boolean;
  reqs = [] as any[];
  counter = {
    total: 0,
    ended: 0,
    error: 0,
    success: 0,
  } as Counter;

  init() {
    this.send(0);
   
  }

  @watch('counter.ended')
  endedChange (ended: number) {
    if (ended === this.counter.total) {
      this.quite();
    }
  }

  constructor () {
    this.init();
  }

  async cancle () {
    if (this.isStop) {
      this.isShow = true;
      return;
    }
    this.hasStopDialog = true;
    const res = await this.showStopDialog();
    this.hasStopDialog = false;
    // 取消终止
    if (res === ShowStopDialogRes.sure) {
      this.isStop = false;
      if (this.counter.ended === this.counter.total) {
        this.counter.total = this.reqs.length;
      }
      return;
    }
    // 确定终止
    if (this.counter.total === this.counter.total) {
      this.quite();
    }
  }

  stop () {
    // todo
  }
  quite () {
    this.resetAndDectory();
  }

  async send (index: number) {
    if (this.isStop) return;

    const req = this.reqs[index];
    if (req) return;

    const res = await this.fetchApi(req);

    if (res.Code !== 200) {
      alert('bug,还不修!');
    }

    if (this.isStop) return;

    this.send(++index);
  }

  async fetchApi (req: any): Promise<CodeObj<null>> {
    let res: Promise<CodeObj<null>>;
    // todo
    return res;
  }
  // 暂停弹窗
  async showStopDialog () {
    let ret: ShowStopDialogRes;
    // todo
    return ret;
  }
  // 重置并销毁
  resetAndDectory () {
    // todo
  }
}

猜你喜欢

转载自www.cnblogs.com/liangcheng11/p/9119805.html