Last active
April 21, 2022 17:42
-
-
Save Zamiell/5d5441de366d4d0c3d981296b14e4a58 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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