asb_cloud_front/src/utils/queue.ts

29 lines
640 B
TypeScript

export type TaskHandler<T> = () => T | PromiseLike<T>
export type Queue<T> = {
push: (task: TaskHandler<T>) => Promise<T>
readonly length: number
}
export const makeTaskQueue = <T,>(): Queue<T> => {
let pending: Promise<T | void> = Promise.resolve()
let count: number = 0
const run = async (task?: TaskHandler<T>) => {
count++
try {
await pending;
} finally {
count--
return Promise.resolve().then(task);
}
}
return {
push: (task: TaskHandler<T>) => pending = run(task),
length: count,
}
}
export default makeTaskQueue