示例工程 38-schema-migrations-concurrency

38-schema-migrations-concurrency/app/shared/write-queue.ts

typescript · 0.5 KB

export type WriteQueue = {
  run<T>(task: () => Promise<T> | T): Promise<T>;
  pending: () => number;
};

export function createWriteQueue(): WriteQueue {
  let tail: Promise<unknown> = Promise.resolve();
  let pending = 0;
  return {
    run<T>(task: () => Promise<T> | T): Promise<T> {
      pending += 1;
      const result = tail.then(task);
      tail = result.then(
        () => {
          pending -= 1;
        },
        () => {
          pending -= 1;
        },
      );
      return result;
    },
    pending: () => pending,
  };
}