Skip to content

Instantly share code, notes, and snippets.

@Zamiell
Last active April 21, 2022 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zamiell/5d5441de366d4d0c3d981296b14e4a58 to your computer and use it in GitHub Desktop.
Save Zamiell/5d5441de366d4d0c3d981296b14e4a58 to your computer and use it in GitHub Desktop.
export default class Queue {
private items: Array<() => Promise<void>> = [];
private waker: (() => void) | null = null;
constructor() {
this.processQueue().catch((err) => {
throw new Error(`Failed to process a queue: ${err}`);
});
}
private async processQueue(): Promise<void> {
const functionExecutor = this.items.shift();
if (functionExecutor === undefined) {
await this.sleep();
} else {
await functionExecutor();
}
}
private async sleep() {
await new Promise<void>((resolve) => {
this.waker = resolve;
});
this.waker = null;
}
async enqueueAndWait<T>(asyncFunc: () => Promise<T>): Promise<T> {
const promise = new Promise<T>((resolve, reject) => {
const functionExecutor = async () => {
try {
resolve(await asyncFunc());
} catch (e) {
reject(e);
}
};
this.items.push(functionExecutor);
});
if (this.waker !== null) {
this.waker();
}
return promise;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment