Created
February 2, 2022 00:01
-
-
Save timotree3/a46d382846070046b7faf231075c3242 to your computer and use it in GitHub Desktop.
JS Queue
This file contains 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 { | |
constructor() { | |
// All fields should be private | |
this.waker = null | |
this.kill = false | |
this.items = [] | |
this.killed = this.attend() | |
} | |
async enqueue_and_wait(async_fn) { | |
const promise = new Promise((resolve, reject) => this.items.push(async () => { | |
try { | |
resolve(await async_fn()) | |
} catch (e) { | |
reject(e) | |
} | |
})) | |
if (this.waker) { | |
this.waker() | |
} | |
return await promise | |
} | |
async close() { | |
// This code path is not tested | |
this.kill = true | |
if (this.waker) { | |
this.waker() | |
} | |
await this.killed | |
} | |
// This method should be private | |
async sleep() { | |
await new Promise(resolve => this.waker = resolve) | |
this.waker = null | |
} | |
// This method should be private | |
async attend() { | |
while (!this.kill) { | |
if (this.items.length > 0) { | |
await this.items.shift()() | |
} else { | |
await this.sleep() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment