Skip to content

Latest commit

 

History

History
executable file
·
49 lines (43 loc) · 1.23 KB

异步串行钩子.md

File metadata and controls

executable file
·
49 lines (43 loc) · 1.23 KB

前言

class AsyncSeriesHook {
  tasks: Function[];
  constructor() {
    this.tasks = [];
  }

  next(task: Function) {
    this.tasks.push(task);
    return this;
  }

  callAsync(...args: any) {
    const finalCallback = args.pop();
    const next = (idx: number, lastResult = null) => {
      if (idx === this.tasks.length) {
        finalCallback(lastResult, null);
        return;
      }
      const task = this.tasks[idx];
      task(...args, lastResult).then(
        (res: any) => {
          next(idx + 1, res);
        },
        (err: any) => finalCallback(null, err),
      );
    };
    next(0);
  }

  run(...args: any) {
    return new Promise((resolve, reject) => {
      const finalCallback = (res: any, err: any) => {
        if (err) {
          reject(err);
        } else {
          resolve(res);
        }
      };
      this.callAsync(...args, finalCallback);
    });
  }
}

完整的 demo 请看👉 在线效果预览, 查看示例代码请点击此处