forked from ddrilling/asb_cloud_front
29 lines
640 B
TypeScript
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
|